最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to get the number of children div in css or sass - Stack Overflow

programmeradmin1浏览0评论

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.

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.

Share Improve this question edited Feb 21, 2022 at 17:30 Victoria Ruiz 5,0133 gold badges24 silver badges42 bronze badges asked Feb 15, 2018 at 12:32 philip_nunoophilip_nunoo 9384 gold badges10 silver badges22 bronze badges 7
  • are you trying to check if this ul has children or not ??? – andrew s zachary Commented Feb 15, 2018 at 12:34
  • 4 I don't think you can "get" anything in CSS. You define rules, rules apply. It's only one way. – Jeremy Thille Commented Feb 15, 2018 at 12:34
  • @fcalderan I'm looking for the count to count the number of child to dynamically change css-properties like padding withing the child class. – philip_nunoo Commented Feb 15, 2018 at 12:36
  • u can do that with sass functions and loop – andrew s zachary Commented Feb 15, 2018 at 12:38
  • @collision do you mind elaborating a specific example editing your question? What should change under what condition? – Fabrizio Calderan Commented Feb 15, 2018 at 12:42
 |  Show 2 more comments

4 Answers 4

Reset to default 10

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/

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

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

If you add a numbered class-name to the .child elements, say child1, child2, etc... then you can loop over the set in this manner:

$maxElements: 100;
@for $i from 1 to $maxElements {
  .child#{$i} {
    //..do something to child element, eg: 
    color: darkorange !important;
  }
}

Not the nicest way as you have to set a max, and some processing happens that is empty, but it seems to work.

发布评论

评论列表(0)

  1. 暂无评论