Is there any way to use the nth-child
value as a SASS variable ?
Examples of use :
div:nth-child(n) {
content: '#{$n}'
}
div:nth-child(n) {
background: rgb(#{$n}, #{$n}, #{$n});
}
Writing Complex :nth-child() SelectorsIt works exactly the same as :nth-child except that it starts from the end of the parent. For example, you can select the first three children of a parent by using the selector :nth-child(-n + 3) . You can use :nth-last-child(-n + 3) to select the last three.
Definition and UsageThe :nth-child(n) selector matches every element that is the nth child of its parent. n can be a number, a keyword (odd or even), or a formula (like an + b). Tip: Look at the :nth-of-type() selector to select the element that is the nth child, of the same type (tag name), of its parent.
The basic syntax for defining a variable is simple: Just use a $ before the variable name and treat its definition like a CSS rule: Sass Variable Syntax: $<variable name>:<value>; The following declares a variable named large-font.
The :nth-last-child selector allows you select one or more elements based on their source order, according to a formula. 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 elements.
I don't think there's a way to do exactly that. But you can use @for
directive to loop through a known number of elements:
$elements: 15;
@for $i from 0 to $elements {
div:nth-child(#{$i + 1}) {
background: rgb($i, $i, $i);
}
}
You could use a mixin like this:
@mixin child($n) {
&:nth-child(#{$n}){
background-color:rgb($n,$n,$n);
}
}
div{
@include child(2);
}
The compiled css looks like:
div:nth-child(2) {
background-color: #020202;
}
See an example here
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