Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using SASS Variables within nth-child?

Tags:

sass

I have a grid set up of thumbnail images, currently 4 thumbs per row. To make sure they line up i have this snippet of code:

li:nth-child(5) { margin-left: 0;} 

What I have tried to do is this but I am getting a syntax error:

 $galleryGrid: 5;     li:nth-child($galleryGrid) { margin-left: 0;} 

If I wanted to alter the nth-child to use another value, such as 10 (so I can have 8 thumbs in a row), I assumed this would work. Is this not possible or am I just doing incorrectly?!

Thanks in advance for you help.

like image 890
Huw Rowlands Avatar asked Oct 02 '12 17:10

Huw Rowlands


People also ask

How do you target the nth child in sass?

Writing Complex :nth-child() Selectors It 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 I select nth child in SCSS?

You can pass in a positive number as an argument to :nth-child() , which will select the one element whose index inside its parent matches the argument of :nth-child() . For example, li:nth-child(3) will select the list item with an index value 3; that is, it will select the third list item.

How do I select a specific Nth child in CSS?

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.


1 Answers

You need to use variable interpolation to allow nth-child to be a variable.

$galleryGrid: 5; li:nth-child(#{$galleryGrid}) { margin-left: 0;} 

Generates

li:nth-child(5){margin-left:0} 

This markup is fine if you have absolute control over the images and layout to ensure that your elements always wrap in such a way that every 5th one begins a new row. If you cannot make such guarantees, setting negative margins on the parent element is a better way to go.

like image 131
cimmanon Avatar answered Oct 09 '22 11:10

cimmanon