Using SASS Variables within nth-child?

2019-01-18 17:39发布

问题:

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.

回答1:

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.



标签: sass