Hajime, the duck guy

Sunday, April 14, 2024, by Hajime Yamasaki Vukelic

Here's a bookmarklet that lets you get the viewport width in rems.

Here's the bookmarklet:

javascript:alert(innerWidth/parseInt(getComputedStyle(document.documentElement).getPropertyValue('font-size'),10))

Just create a bookmark and use the above as the link. Or you can drag the following link into your bookmark bar:

Viewport width in rem

How it works

When you click the bookmark, you will see an alert with a number. This number represents the viewport width in rem.

The code gets the computed font-size property of the document.documentElement. This is going to be the same as the browser's default font size (or whatever you have set in the settings) unless you override it in the CSS by setting a font-size for the <html> element (don't do that ever!).

It divides the window.innerWidth with the computed font-size to get the width in rem.

Simple as that.

Why tho?

You may be wondering why we'd need a viewport width in rem to begin with. The reason we need this value is for more robust responsive layouts.

I'm not going into details about how it all works, because the point of this post is the bookmarklet. Here's an executive summary:

Media queries (and, in fact, any dimension) that uses relative units like em or rem will scale with the font size setting in the browser. This makes the layout more robust. If the user is using a non-default font size, the breakpoints will adjust themselves accordingly and the correct one will be used for a given font-screen size combination.

For more information, refer to There's no such thing as a desktop screen.

Posted in Tools
Back to top