What is postcss-for?
The postcss-for package is a PostCSS plugin that allows you to use for-loops in your CSS. This can be particularly useful for generating repetitive styles dynamically, reducing the need for manual duplication and making your stylesheets more maintainable.
What are postcss-for's main functionalities?
For-loop in CSS
This feature allows you to use a for-loop syntax in your CSS to generate repetitive styles. In the example, it creates three classes (.item-1, .item-2, .item-3) with widths of 10px, 20px, and 30px respectively. This reduces the need for manually writing repetitive CSS rules.
@for $i from 1 to 3 {
.item-$i {
width: $(i) * 10px;
}
}
Other packages similar to postcss-for
postcss-each
postcss-each is a PostCSS plugin that provides a similar functionality to postcss-for by allowing you to iterate over arrays and objects in your CSS. While postcss-for focuses on simple for-loops, postcss-each offers more flexibility with its ability to handle complex data structures.
postcss-mixins
postcss-mixins allows you to define and use mixins in your CSS, which can include loops and other logic. While it doesn't specifically focus on for-loops like postcss-for, it provides a broader set of tools for creating reusable and dynamic styles.
postcss-nested
postcss-nested enables nesting of CSS rules, which can be combined with postcss-for to create more organized and maintainable stylesheets. While it doesn't provide looping capabilities, it complements postcss-for by allowing nested structures that can benefit from loop-generated classes.
PostCSS For Plugin
PostCSS plugin that enables @for
loop syntax in your CSS.
Try it out!
You can try postcss-for directly from codepen.
Just choose PostCSS as a preprocessor and pick desired plugin from the list.
Usage
postcss([ require('postcss-for') ])
Note, that unlike the Sass @for
, postcss-for in the example below iterates from 1 to 3 inclusively.
@for $i from 1 to 3 {
.b-$i { width: $(i)px; }
}
.b-1 {
width: 1px
}
.b-2 {
width: 2px
}
.b-3 {
width: 3px
}
This plugin must be set before postcss-nested and postcss-simple-vars.
Therefore dollar variable cannot be used as a loop range parameter.
If you do want to use predefined range parameters though, consider using postcss-custom-properties with postcss-at-rules-variables, or look into this postcss-for fork.
More features
By
keyword is available:
@for $i from 1 to 5 by 2 {
.b-$i { width: $(i)px; }
}
.b-1 {
width: 1px
}
.b-3 {
width: 3px
}
.b-5 {
width: 5px
}
Locality of variables in nested loops is supported:
@for $x from 1 to 2 {
@for $y from 1 to $x {
@for $z from $y to $x {
.c-$(x)-$(z)-$(y) { padding: $(x)em $(z)em $(y)em; }
}
}
}
.c-1-1-1 {
padding: 1em 1em 1em
}
.c-2-1-1 {
padding: 2em 1em 1em
}
.c-2-2-1 {
padding: 2em 2em 1em
}
.c-2-2-2 {
padding: 2em 2em 2em
}
See PostCSS docs for examples for your environment.