Creating a pixels to rem converter using Javascript

Subscribe to my newsletter and never miss my upcoming articles

Listen to this article

While I was studying for my web development course, I came across a section where the instructor was explaining the benefits in using rem instead of pixels when indicating sizes and spacing. As accessibility becomes more prevalent than ever, it’s important to understand the usage in using rem over pixels.

In general, rem stands for “root em.” From a designer’s perspective, utilising rem over pixels would benefit the user as you’ll be taking into consideration on their browser’s specifications. If you were to place most of the font sizes and spacings into pixels, it may look good aesthetically on your end. However, if the user decides to use the browser zoom option, it would end up looking distorted. Having rem in replace of pixels would guarantee the user’s experience when they view your website on their devices. I found this article to be helpful when understanding the rem vs em vs px debate.

This idea on creating a pixels to rem converter using Javascript was based off on my conversation with my husband. I found out that his current job required him to do some research on the differences between pixels and rem and he had no clue about it. I decided to create this simple script based off from W3Schools length converter as an introductory step to work on Javascript projects. Previously, I’ve tinkered with other options on whether or not if I wanted to create a form or added some more fancier options. But I found this approach to be simpler as I wanted the output to be displayed in real time when the user inputs the pixels number.

Here is my CodePen where you can play around with the script:

What I’ve learned during this process in creating this converter:

  1. The formula for the conversion was simple to implement. For every 16px, it equates to 1rem. If you wanted the equivalent of 32px, then it would be 2rem (32/16 = 2).

  2. Initially, I was a bit confused on the purpose of using the this.value option until I realised that it simply meant that it was capturing the value from the input based on what the user entered. The oninput and onchange is what helped make the calculation happen in realtime.

  3. With the entire interface, I reflected all of the values that were initially in px and converted them to rem as I wanted to make sure it was responsive on the browser and mobile device. I kept it simple but added a personal touch on the page. You can tell by now that my favourite colour is purple.

  4. The only gripe I have about the script is the area being initially blank next to rem. I’m pretty sure this can be improved, but I’ll have to tinker around with the style options in making the area visible even with no number added in it.

Let me know your thoughts! If you want to follow up on my web development journey, be sure to connect with me via my Twitter profile.

No Comments Yet