Technically, CSS doesn’t have the ability to count an element’s siblings. However, Heydon recently showed us what he calls quantity queries: a clever combination of :nth-last-child(), :first-child, and ~ to style elements based on how many elements are in a single parent. Have a look at that A List Apart article and my interactive demo on CodePen to get a feel for what’s going on.
How Quantity Queries Work
Here’s the basic gist of quantity queries: by using :nth-last-child($n) and :first-child together, you can identify an element that is a certain number from the end of its siblings and the first child of its parent. The number from the end tells us the number of siblings. For example, the selector :nth-last-child(6):first-child will only select the first element in a group of 6 elements. If you select that element and all of its following siblings using ~, you can write custom CSS for the group of siblings based on how many there are.
[code language="sass"] :nth-last-child(6):first-child, :nth-last-child(6):first-child ~ * { // unique CSS for elements when there are 6 of these } [/code]
This code lets you target a specific count, but let’s say you want to change styles when there are “at least” or “less than” a certain number. You can do that by modifying the :nth-last-child() value. To target groups of at least 6 items, use :nth-last-child(n + 6):first-child and for groups of less than 6, use :nth-last-child(-n + 6):first-child.
Continue reading %Using Sass for “Quantity Queries”%
by James Steinbach via SitePoint
No comments:
Post a Comment