What I'm trying to achieve, is to simply loop over and create a selector based on how many columns a variable has.
$numberOfColumns: 16;
.gridContainer {
@for $i from 1 through $numberOfColumns {
.grid_#{$i} @if $i != $numberOfColumns {,}
{position:relative;}
}
}
This obviously doesn't work.
I'm trying to output something like this:
.grid_1,.grid_2,.grid_3,.grid_4,.grid_5,.grid_6,.grid_7,.grid_8,.grid_9,.grid_10,.grid_11,.grid_12,.grid_13,.grid_14,.grid_15,.grid_16 {position:relative;}
Any help would be great.
You can simply use join
to create a variable containing all the comma-separated classes and use that afterwards. Here is how:
$numberOfColumns: 16;
$classes: ();
@for $i from 1 through $numberOfColumns {
$classes: join($classes, unquote(".grid_#{$i} "), comma);
}
.gridContainer {
#{$classes} { position:relative; }
}
Produced output:
.gridContainer .grid_1, .gridContainer .grid_2, .gridContainer .grid_3, .gridContainer .grid_4, .gridContainer .grid_5, .gridContainer .grid_6, .gridContainer .grid_7, .gridContainer .grid_8, .gridContainer .grid_9, .gridContainer .grid_10, .gridContainer .grid_11, .gridContainer .grid_12, .gridContainer .grid_13, .gridContainer .grid_14, .gridContainer .grid_15, .gridContainer .grid_16 {
position:relative;
}
Here is a more thorough explanation of the same concept: http://portfolio.miphe.com/showcase/sass-dry-selectors/
A situation like this typically calls for using a placeholder selector:
Sometimes you’ll write styles for a class that you only ever want to
@extend
, and never want to use directly in your HTML. This is especially true when writing a Sass library, where you may provide styles for users to@extend
if they need and ignore if they don’t.[...]
Placeholder selectors look like class and id selectors, except the
#
or.
is replaced by%
. They can be used anywhere a class or id could, and on their own they prevent rulesets from being rendered to CSS.
placeholders @ sass-lang.com
With a placeholder selector, you can collect all of the properties that are common to all grid columns in a single rule:
%grid-column {
// common column properties...
}
Then use the @extend
directive to add .grid-container .grid-i
selectors to the placeholder rule:
$num-grid-cols: 2;
.grid-container {
@for $i from 1 through $num-grid-cols {
.grid-#{$i} {
@extend %grid-column;
// grid-$i specific properties...
}
}
}
The resultant CSS will look like this:
.grid-container .grid-1, .grid-container .grid-2 {
// common column properties...
}
.grid-container .grid-1 {
// grid-1 specific properties...
}
.grid-container .grid-2 {
// grid-2 specific properties...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With