Make Font Sizing with REM easy with SCSS or LESS

Posted

Font sizing with REM using LESS or SCSS

Before you start worrying, this isn’t going to be a huge blog post about the best methods for sizing text for the web….there’s already plenty of those around! I also realise that there’s been plenty of debate around which font unit is best, but in all honesty I don’t care about that. I’ve tried using px, em and rem and have settled on using rem’s for the font sizing on most of my projects.

I found that rem was easier than using em and certainly helped when building a responsive website. The two annoyances with using rem is having to convert pixels font sizes into rem units and also having to set pixel fallbacks for the older browsers that don’t support it. Having to do this every time you need to write a font size can get boring, real quick!

If you use SCSS or LESS then you’re in luck as you can use the following mixin to save yourself a lot of time!

CSS

html {
font-size: 62.5%; /* Sets up the Base base font-size to an equivalent of 10px - Doing this makes it a lot easier to convert px sizes into rem sizes. */
}

SCSS – Mixin

@mixin font-size($sizeValue: 1.6) {
font-size: ($sizeValue * 10) + px;
font-size: $sizeValue + rem;
}

SCSS – Usage

p {
@include font-size(13);
}

LESS – Mixin

.font-size(@sizeValue){
@remValue: @sizeValue;
@pxValue: (@sizeValue * 10);
font-size: ~"@{pxValue}px";
font-size: ~"@{remValue}rem";
}

LESS – Usage

p {
.font-size(13);
}

There we go, font-sizing made sexy…alright, maybe that’s not the right word to use when talking about the size of type, but these mixins will give us resizable text in rem-compliant browsers, with a pixel-based fallback for older ones — a match made in heaven.

2 Comments

I think you should check out your formulas (at least as far as less is concerned):
.font-size(@sizeValue){
@remValue: (@sizeValue * .1);
@pxValue: @sizeValue;
font-size: ~”@{pxValue}px”;
font-size: ~”@{remValue}rem”;
}
Should be the correct math…

Karl von Selm

.font-size(@sizeValue) {
@remValue: @sizeValue * 0.0625;
@pxValue: (@remValue * 16);
font-size: ~”@{pxValue}px”;
font-size: ~”@{remValue}rem”;
}

Comments are closed.