Preface
Now a tricky question, about custom tailored preprocessor.
What if, I prefer indentation style instead of bracket style?
PostCSS has a SugarSS
parser that has a nice indentation style,
just like SASS
or Stylus
.
The issue is, SugarSS
does not have any capability as good as PreCSS
,
such as $variables
, @for
, @each
and @if
.
The beauty of postcss
is that you can mix tools together.
Using SugarSS
along with PreCSS
,
enable indentation style from SugarSS
,
while at the same time preserve feature from PreCSS
.
Configuration
We are using this configuration:
module.exports = {
parser: 'sugarss',
plugins: [
require('postcss-strip-inline-comments'),
require('postcss-each'),
require('precss'),
require('postcss-prettify'),
],
}
If you haven’t read the configuration guidance yet, I suggest you to take one step behind to this article:
Instead of
syntax: 'postcss-scss',
We use
parser: 'sugarss',
Precaution
You cannot use multiline in the syntax.
Since this mix approach is more like a workaround than best practice, there is a drawback.
Consider this example below:
PreCSS Source
Consider this @for loop below:
// variable initialization
$loop-begin: 5;
$loop-stop: 25;
$interval: 5;
// loop
@for $cursor from $loop-begin
to $loop-stop by $interval {
.m-$(cursor) {
margin: $(cursor)px;
}
}
SugarSS Source
The correct translation by removing semicolons and brackets is shown as below:
// variable initialization
$loop-begin: 5
$loop-stop: 25
$interval: 5
// loop
@for $cursor from $loop-begin to $loop-stop by $interval
.m-$(cursor)
margin: $(cursor)px
The Difference
You should write the whole statement, as oneliner as below:
@for $cursor from $loop-begin to $loop-stop by $interval
.m-$(cursor)
margin: $(cursor)px
And this one below would be fail:
@for $cursor from $loop-begin
to $loop-stop by $interval
.m-$(cursor)
margin: $(cursor)px
Because it will be translated as
@for $cursor from $loop-begin;
to $loop-stop by $interval {
.m-$(cursor) {
margin: $(cursor)px;
}
}
Note that semicolon after the word begin
.
This little guy will break your loop statement.
Complete Example
How about complete example? The final spacing loop classes.
SugarSS Source
// variable initialization
$loop-begin: 0
$loop-stop: 25
$interval: 5
@for $cursor from $loop-begin to $loop-stop by $interval
@each $prop, $name in (margin, padding), (m, p)
.$(name)-$(cursor)
$(prop): $(cursor)px !important
@each $side, $subname in (top, bottom, left, right), (t, b, l, r)
.$(name)-$(subname)-$(cursor)
$(prop)-$(side): $(cursor)px !important
.$(name)-y-$(cursor)
@each $side in (top, bottom)
$(prop)-$(side): $(cursor)px !important
.$(name)-x-$(cursor)
@each $side in (left, right)
$(prop)-$(side): $(cursor)px !important
CSS Result
This will result, about the same output as previous precss
example.
Conclusion
These spacing classes is ready to serve.
What do you think ?