Heads up! This blog post hasn't been updated in over 2 years. CodePen is an ever changing place, so if this post references features, you're probably better off checking the docs. Get in touch with support if you have further questions.
We offer preprocessors for HTML, CSS, and JS on CodePen. You can explore all of them by opening the settings area in each editor to see all the buttons of what is available. One feature that most preprocessors offer is the ability to write a loop. This can be tremendously useful, as, at least HTML and CSS, don’t offer loops.
Here’s how to do it in the languages we support that offer them:
A Loop in Haml
See the Pen Loop with Haml by Chris Coyier (@chriscoyier) on CodePen
A Loop in Jade
See the Pen Loop with Jade by Chris Coyier (@chriscoyier) on CodePen
A Loop in Slim
See the Pen Loop with Slim by Chris Coyier (@chriscoyier) on CodePen
A Loop in SCSS
See the Pen Loop with SCSS by Chris Coyier (@chriscoyier) on CodePen
A Loop in Sass
See the Pen Loop with SCSS by Chris Coyier (@chriscoyier) on CodePen
A Loop in LESS
See the Pen Loop with LESS by Chris Coyier (@chriscoyier) on CodePen
A Loop in Stylus
See the Pen Loop with Stylus by Chris Coyier (@chriscoyier) on CodePen
A Loop in CoffeeScript
See the Pen Loop with Stylus by Chris Coyier (@chriscoyier) on CodePen
A Loop in LiveScript
See the Pen Loop with LiveScript by Chris Coyier (@chriscoyier) on CodePen
Important Note about Loops
If you go too crazy with the looping (like a hundred thousand iterations or something) it will take a long time for CodePen to process it. If it takes too long, we’ll time out the request and it will fail. There is nothing that can be done about that, sorry.
Bonus Facts
- Most of these languages also support loops over already existing arrays or objects, I’m just using a simple
for
loop here for demonstration. - Using a loop instead of hand-written repetitive code is less error-prone
- In HTML, if you do want to hand-write the repetitive code, you can at least use Emmet and do stuff like
div.item-$*5
then press TAB to expand it out the five times. - You can nest loops. Helpful for multi-dimensional things like tables.
- Loops are particularly useful on CodePen for fancy visual demos with lots of elements and variation.