Table of Content
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.
Let’s assume we use col-N
for the column name, so one
becomes col-1
, and so on.
Now we define how many columns count in total with a variable.
1$columns-count: 12;
Now we can use the @for $i from A through B
syntax to define the columns:
And we would get this compiled CSS with all the percentages calculated.
1@media screen and (min-width: 500px) { 2 .col-1 { 3 width: 8.33333%; } 4 5 .col-2 { 6 width: 16.66667%; } 7 8 .col-3 { 9 width: 25%; } 10 11 .col-4 { 12 width: 33.33333%; } 13 14 .col-5 { 15 width: 41.66667%; } 16 17 .col-6 { 18 width: 50%; } 19 20 .col-7 { 21 width: 58.33333%; } 22 23 .col-8 { 24 width: 66.66667%; } 25 26 .col-9 { 27 width: 75%; } 28 29 .col-10 { 30 width: 83.33333%; } 31 32 .col-11 { 33 width: 91.66667%; } 34 35 .col-12 { 36 width: 100%; } 37}
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:
1$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:
1nth($numbers-text, 1);
Now we can define our columns with the English word by using this technique:
And this is what we got, assume the $columns-count
is 4.
This article from Hugo provides a detail usage exampels on the Scss list.
What’s next? We’re going to take a look at “Chapter 6 – Typography”.