Using SASS Variables within nth-child?

2019-01-18 18:16发布

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.

标签: sass
1条回答
我想做一个坏孩纸
2楼-- · 2019-01-18 18:35

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.

查看更多
登录 后发表回答