6

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.

7
  • are you trying to check if this ul has children or not ??? 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. 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. Feb 15, 2018 at 12:36
  • u can do that with sass functions and loop Feb 15, 2018 at 12:38
  • @collision do you mind elaborating a specific example editing your question? What should change under what condition? Feb 15, 2018 at 12:42

4 Answers 4

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/

3
  • 3
    this iterates from 1 through 8. If I'm to get this. The problem is u don't know the number of children at a point in time. And may be greater or less than 8 Feb 15, 2018 at 16:35
  • You won't be able to get a number via CSS. You can change the number 8 to something that you consider a safe bet. Otherwise, you'll have to us JS to add an inline padding to each li Feb 15, 2018 at 18:16
  • Will you be giving a specific padding to each child, or will there be some sort of pattern in how you assign it? Feb 15, 2018 at 18:18
1

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

0

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
0

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.