Converting Your Typographic Units with Sass

Originally published at: http://www.sitepoint.com/converting-typographic-units-sass/

Long ago, in the dense mists of the Internet’s past, intrepid adventurers tackled danger in much the same way: sling a fixed 960px layout, fight in a set grid and fire their typography in pixels to ward off evil.

Responsive web design has since changed all that, bringing us out of that dense mist and into an age of enlightenment. And yet, using typography on the web is still a pain at times. With the push from pixels or points to percentages and ems, I find myself continuously having to Google “pixel to percentange conversion chart” or something similar at the beginning of every project and often during as well.

In frustration, I turned to the power of Sass to forge a new, all-encompassing function in my quest to vanquish these problems, and today we’re going to go through building that function.

It’ll allow us to convert freely between pixels, ems, and percentages without having to consult a chart every time and, hopefully, alleviate a lot of our headaches in the process.

Continue reading this article on SitePoint

Nice function.

I would recommend to use a more configurable approach using the base size of the html for converting, using the unit in the value for converting and output errors if input is wrong.

You can see my suggestion here https://gist.github.com/npostulart/4de142bf2874c1802a15

I didn’t updated the pt convert part yet as I need to figure out the correct values for converting.

Hope you like my changes to your code.

Ohai. Nice article.

One suggestion: you might want to use % rather than percent since unit(1%) returns %, not percent. :slight_smile:

Hey @npostulart. Unfortunately, your code incorrectly handles units by treating these as strings. More information in a recent SitePoint article: http://www.sitepoint.com/understanding-sass-units/. Cheers. :slight_smile:

Hi @HugoGiraudel, thanks for your hint. I updated my Gist to better handle the unit conversion.
The only small issue I cannot solve is using '%' for comparison as % alone would lead to an Invalid CSS error.

Hope I did it better this time. :smile:

unit(1%)?

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.