Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use nth-child value as a SASS variable

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});
}
like image 717
zessx Avatar asked Nov 21 '13 11:11

zessx


People also ask

How do you use the nth child in sass?

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.

How do you use the nth of a child?

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.

How do you use variables in sass?

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.

Can I use Nth last child?

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.


2 Answers

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);
  }
}
like image 92
myajouri Avatar answered Oct 18 '22 19:10

myajouri


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

like image 32
Jens Cocquyt Avatar answered Oct 18 '22 20:10

Jens Cocquyt