How to generate h1 – h6 font sizes using LESS CSS

I’ve been a big fan of LESS ever since I started using it. I even created a free theme just to play around with it.  While working on a new free theme with my company 8BIT I wanted to figure out how to use LESS to generate the header elements and  different font sizes automatically.  It took a bit of trial and error ( mainly because I think there is a bug in LESS that caused an issue).

My solution

@iterations: 6;

.h(@index) when (@index > 0) {
h@{index} {
        font-size: 72px - @index*10;
}
.h(@index - 1);
}
.h(0) {}
.h(@iterations);

output

h6 {
  font-size: 12px;
}
h5 {
  font-size: 22px;
}
h4 {
  font-size: 32px;
}
h3 {
  font-size: 42px;
}
h2 {
  font-size: 52px;
}
h1 {
  font-size: 62px;
}

I really wish it would output the other way around…

explenation

I am basically creating a Loop using 6 @iterations: (h1-h6) I’m starting this loop at 0 with a font size of 72px and it will subtract by *10 for each iteration. I ran into a bug where it would only accept classes.. therefore it would spit out .h1 .h2 .h3… almost about to give up I realized if I used a regular “h” for what was going to be spit out it would work!

You can also use this for color variations or even create a simple grid using divs and classes.

5 comments on “How to generate h1 – h6 font sizes using LESS CSS

  1. This should give it to you in the correct order…

    @iterations: 1; .h(@index) when (@index < 7) { h@{index} { font-size: 72px – @index*10; } .h(@index + 1); } .h(0) {} .h(@iterations);

Leave a Reply

Your email address will not be published. Required fields are marked *