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?
Yes, Its possible through CSS but only if you can fix the elements in every row.
Since you haven't provided your case, here is an example.
Suppose, your elements are stacked up in a ul
and li
pattern and are three lists in a row, then you can use the following css snippet.
li:first-child, li:nth-child(3n+1) {
background: red;
}
Demo
Unfortunately this is not possible with CSS alone. I ran into this issue when I wanted to ensure that the left most floated elements on each row always start on a new line.
I know you were looking for a CSS solution but I wrote this jQuery plugin that identifies the first element on each visual row and applies "clear:left" to it (you could adapt it to do anything).
(function($) {
$.fn.reflow = function(sel, dir) {
var direction = dir || 'both';
//For each conatiner
return this.each(function() {
var $self = $(this);
//Find select children and reset clears
var $elems = sel ? $self.find(sel) : $self.children();
$elems.css('clear', 'none');
if ($elems.length < 2) { return; }
//Reference first child
var $prev = $elems.eq(0);
//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.css('clear', direction);
}
//Move on to next child
$prev = $elem;
});
});
};
})(jQuery);
See this codepen example http://codepen.io/lukejacksonn/pen/EplyL
No, there is no selector for this, you'll need to use JavaScript.
For reference, the following is a good reference to CSS selectors:
http://www.w3.org/wiki/CSS/Selectors