问题
Is it possible to determine number of children of any container using any SASS function?
For example, I have a container which has 3 columns:
<div class="columns columns_3">
<div class="column"></div>
<div class="column"></div>
<div class="column"></div>
</div>
For this container, I want to implement a mixin which is +columns_3
But if the container has nth number of children, mixin will be +columns_n
回答1:
What you want is to know how many childs haves an element and set the right class to it. You need Javascript to detect the number of childs, HTML and CSS.
SCSS
.element {
$width: 100%;
width: $width;
div {
height: 100px;
float: left;
border:1px solid #000;
box-sizing: border-box;
}
@for $i from 1 through 12 {
&--#{$i} div {
width: $width/$i;
}
}
}
var element = document.getElementsByClassName('element')[0];
var childs = element.childElementCount;
element.classList.add("element--"+childs);
.element {
width: 100%;
}
.element div {
height: 100px;
float: left;
border: 1px solid #000;
-webkit-box-sizing: border-box;
box-sizing: border-box;
}
.element--4 div {
width: 25%;
}
<div class="element">
<!-- childs -->
<div></div>
<div></div>
<div></div>
<div></div>
</div>
回答2:
Well if you have a range, you could potentially use a for loop - depending what you need to do. For example:
$gridWidth = 100%;
@for $numItems from 1 through 12 {
.columns_#{$numItems} {
.column {
width: $gridWidth / $numItems;
}
}
}
回答3:
I think you can make this :
@function number(val) { @return val };
@mixins +columns_#{number(10)} {
// Your code;
}
I'm not sure I understand what you explain.
来源:https://stackoverflow.com/questions/47895004/is-it-possible-to-determine-number-of-children-of-any-container-using-any-sass-f