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.
- 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
4 Answers
Reset to default 10Neither 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.