CSS selector for first element of visual (block reflow) row

Viewed 9668

Is there a CSS selector for the first element of every visual row of block items? That is, imagine having 20 block elements such that they flow across multiple lines to fit in their parent container; can I select the leftmost item of each row?

It's doable in JavaScript by looking at the top position of all of the elements, but is it possible in plain CSS?

4 Answers

Based on the work by @lukejacksonn

This one adds or removes a class on window resize.

(function ($) {
  $.fn.reflow = function (sel, className) {
    if (className == null) throw new Error('className must be set');
    //For each conatiner
    return this.each(function () {
      var $self = $(this);

      //Find select children and reset clears
      var $elems = sel ? $self.find(sel) : $self.children();
      if ($elems.length < 2) {
        return;
      }

      //Reference first child 
      var $prev = $elems.eq(0);

      $elems.each(function () {
        $(this).removeClass(className);
      });

      //Compare each child to its previous sibling 
      $elems.slice(1).each(function () {
        var $elem = $(this);
        //Clear if first on visual row
        if ($elem.position().top > $prev.position().top) {
          $elem.addClass(className);
        }
        //Move on to next child
        $prev = $elem;
      });
    });
  };


  const markFirstRowElement = function () {
    $(".cd-progress-indicator").reflow('li', 'first-row-element');
  }
  $(function () {
    markFirstRowElement();
    $(window).resize(markFirstRowElement);
  });
})(jQuery);
Related