How to get the number of children div in css or sa

2020-04-10 04:44发布

Assuming we have a css list as such

<ul class="parent">
  <li class="child"></li>
</ul>

with the child items being generated based from an iterator. How can you get the number of children within parent in either css or scss.

So I can dynamically modify css attributes like padding based on the nth child.

标签: css sass
3条回答
劫难
2楼-- · 2020-04-10 05:24

Use nth child as explained in this article https://alistapart.com/article/quantity-queries-for-css

查看更多
老娘就宠你
3楼-- · 2020-04-10 05:31

Use direct children selector > and add nth pattern for example:

 p:nth-child(2) // get every 2nd child
 p:nth-child(3n+0) // elements whose index is a multiple of 3
查看更多
我只想做你的唯一
4楼-- · 2020-04-10 05:39

Neither CSS nor SASS will tell you how many items there are in a list. You'll need JS for that.

However, with SASS you can generate the CSS for as many children as you want automatically:

@for $i from 1 through 8 {

    li:nth-child(#{$i} {
        padding-left: $i * 20px
    }
}

Change the number 8 to any number you think will have you covered (10? 100? 1000?).

More info: http://clubmate.fi/for-while-and-each-loops-in-sass/

查看更多
登录 后发表回答