Reputation: 111
In my codebase there are lots of places where data is presented into grids in this way:
.tbl-row-3 {
.item:nth-child(1) {
width: 40%;
}
.item:nth-child(2) {
width: 30%;
}
.item:nth-child(3) {
width: 30%;
}
}
Thing is number of childs and their widths are different everywhere. That's why I need to write it multiple times. And hence was trying to make a formula in my mixins file:
@mixin datagrid(3, 40, 30, 30) {
@for $i from 1 through 3 {
&:nth-child(#{$i}) {
width: ...
}
}
Is it possible in this way, that is mentioning number of childs(3) and then their respective widths(40,30,30)?
If yes, then how? Or is there any other approach possible?
Thanks for the help.
Upvotes: 0
Views: 98
Reputation: 7790
You can write the @mixin
this way:
@mixin datagrid($childNum, $sizes...) {
@for $i from 1 through $childNum {
&:nth-child(#{$i}) {
width: nth($sizes, $i) + 0%;
}
}
}
.tbl-row-3 {
.item {
@include datagrid(3, 40, 30, 30);
}
}
The three dots notation is an argument list, which means that you can pass any number of arguments to the @mixin
. You can then use nth and $i
to retrieve the values.
As an alternative, instead of defining the width of each child every time that you want a grid, you could also consider creating predefined classes such as .width-40
, .width-30
... that would hold the desired styles and then apply them to your elements.
Upvotes: 1