Using loop to define grid
Let’s get deeper on using Scss. We are going to define the grid system by calculation. In our minimal mobile web grid system, we defined the following CSS styles.
@media screen and (min-width: $breakpoint) {
.one {
width: 25%;
}
.two {
width: 50%;
}
.three {
width: 75%;
}
.four {
width: 100%;
}
}
Let’s assume we use col-N
for the column name, so one
becomes col-1
, and so on.
@media screen and (min-width: $breakpoint) {
.col-1 {
width: 25%;
}
.col-2 {
width: 50%;
}
.col-3 {
width: 75%;
}
.col-4 {
width: 100%;
}
}
Now we define how many columns count in total with a variable.
$columns-count: 12;
Now we can use the @for $i from A through B
syntax to define the columns:
@media screen and (min-width: $breakpoint) {
@for $i from 1 through $columns-count {
.col-\#{$i} {
width: 100%/$columns-count * $i;
}
}
}
And we would get this compiled CSS with all the percentages calculated.
@media screen and (min-width: 500px) {
.col-1 {
width: 8.33333%; }
.col-2 {
width: 16.66667%; }
.col-3 {
width: 25%; }
.col-4 {
width: 33.33333%; }
.col-5 {
width: 41.66667%; }
.col-6 {
width: 50%; }
.col-7 {
width: 58.33333%; }
.col-8 {
width: 66.66667%; }
.col-9 {
width: 75%; }
.col-10 {
width: 83.33333%; }
.col-11 {
width: 91.66667%; }
.col-12 {
width: 100%; }
}
Bonus: Using English word for the column name
The loop works because we changed our columns name from .one
, .two
to .col-1
and .col-2
. What if we really want to use the English word to define the column name? Here we go.
A Scss variable can be treated as a list, similar to array. We can separte list via space or comma. Let’s define a list of English number from 1 to 20. I guess it’s enough unless we need more than 20 columns in our grid system:
$numbers-text: one two three four five six seven eight nine ten eleven twelve thirteen fourteen fifteen sixteen seventeen eighteen nineteen twenty;
Then we can access any one of the values via the nth()
Scss function. Just make sure we know that the list index begins at 1 instead of the 0. For example, the first one would be:
nth($numbers-text, 1);
Now we can define our columns with the English word by using this technique:
@media screen and (min-width: $breakpoint) {
@for $i from 1 through $columns-count {
.col-\#{$i},
.\#{nth($numbers-text, $i)} {
width: 100%/$columns-count * $i;
}
}
}
And this is what we got, assume the $columns-count
is 4.
@media screen and (min-width: 500px) {
.col-1,
.one {
width: 25%; }
.col-2,
.two {
width: 50%; }
.col-3,
.three {
width: 75%; }
.col-4,
.four {
width: 100%; }
}
This article from Hugo provides a detail usage exampels on the Scss list.
Comments
no comments yet.