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
A Loop in Jade
A Loop in Slim
A Loop in SCSS
A Loop in Sass
A Loop in LESS
A Loop in Stylus
A Loop in CoffeeScript
A Loop in LiveScript
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.
- Most of these languages also support loops over already existing arrays or objects, I'm just using a simple
forloop 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-$*5then 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.