I wanted to test out if I could inject text via Sass style sheets to see if Sass could somehow support this. Of course, this is already possible in CSS using the nth-child selector and the ::after selector.
Here is a sample of the technique used in this article!
In Sass, however, we can inject text into a large list if we want. This means that the DOM must support the data you want to inject, if you want to inject for example five strings into an array of <ul>
of <li> items, you must also have five items of <li>
Anyways, this is what I ended up with:
$baskerville-font-stack: "Big Caslon", "Book Antiqua", "Palatino Linotype", Georgia, serif !default;
ul li {
font-family: $baskerville-font-stack;
}
$coolitems: ('wig', 'makeup', 'lipstick', 'rouge', 'botox');
@for $i from 1 to length($coolitems)+1{
$coolitem: nth($coolitems, $i);
li:nth-child(#{$i})::before {
content: $coolitem;
}
}
$blogtitle: "Tores jævlige rosablogg";
We first declare an array in Sass using
$coolitems: ('wig', 'makeup', 'lipstick', 'rouge', 'botox')
. We then use the
@for loop in Sass to get loop through this array. The syntax is:
@for $i from 1 to length($coolarray)+1
I had to use the +1 here in my sample.. Then we grab hold of the current item using the nth function, passing in the array $coolitems and specifying the index $i. Now that we have the
item of the $coolitems array, we can set the content CSS property of the n-th child and use the ::before (or ::after) selector. I tried to avoid using the +1 in the for loop, but then the last item of my array was not included in the list.
Note - the use of the
#{$i} in the syntax above. This is called
variable interpolation in Sass. It is similar syntax-wise to variable interpolation in shell scripts, actually. We use it so that we can refer to the variable $i inside the nth-child operator of CSS selector.
And the nth operator is as noted used to grab hold of the nth item of the Sass array.
And your HTML will then look like this:
<ul>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
So you actually now have a list in HTML which is
empty, but the values are
injected through CSS! And Sass makes supporting such scenarios easier. Now why the heck would you want such a thing? I do not know,
I am more a backend developer than webdev frontend developer, it is though cool that you
can load up data into the DOM using Sass and CSS