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?
The :first-child selector allows you to target the first element immediately inside another element. It is defined in the CSS Selectors Level 3 spec as a “structural pseudo-class”, meaning it is used to style content based on its relationship with parent and sibling content.
“select first span in div css” Code Answer's :nth-child(1) { //the benefit of this is you can do it for 2nd, 3rd etc...
The CSS id Selector To select an element with a specific id, write a hash (#) character, followed by the id of the element.
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;
}
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With