25/01/2024
What is CSS rem? How is it different from using pixels, and how do we, at W4, use it in our development process?
Rem is a powerful measurement unit in CSS that can significantly improve the implementation of responsive layouts for you as a front-end developer or a designer.
I want to share how we at W4 effectively integrate rem into our projects, providing you with practical insights,
but first, what is rem?
In opposition to a pixel, which is a fixed unit, rem is a relative unit. It is always relative to the document's font size, which (for some strange reason) is 16px by default.
So, by default, 1rem = 16px.
The rem units' size is declared in the HTML tag. So, if we want 1rem to be equal to 20px we will write (in CSS):
html { font-size: 20px;}
(It's a little confusing at first because CSS uses "font-size" to declare the size of 1rem unit, but you'll get used to it)
Now, let's say we have an image that is 200px long; declaring its width in rems will look like this:
img { width: 10rem; }
What's the big deal, you ask?
It is powerful because we can add different HTML font sizes to different breakpoints and change the entire layout scale without changing each element's size!
Now, how do we at W4 use it?
First, we define the base breakpoint, which everything would be relative to. It's 1920px wide in most cases, depending on the design we get.
Our base rem unit is ALWAYS 10px because it is super easy to convert pixels to rems this way.
So, a square that is 200px high in the design will be declared 20rem in our CSS.
So far, so good.
After we finish writing the entire website's CSS and have constructed all the elements using rems, we decide what our other breakpoints would be.
Most of the time, we use 1366px breakpoint (laptop) and 1280px.
Under the 1366px screen width, we will declare the document's (HTML) font size as 9px. This means that everything on the screen shrinks by 90% simultaneously!
We can add as many breakpoints as we like, scaling the entire layout up or down just as we wish.
It will work like a charm for most designs. Sometimes, we (or the design team) are unhappy with the behavior of some elements' sizes. In that case, we can use pixel units instead or different rem sizes across different resolutions on these elements.
Another nice trick is to compare the rem unit to the screen width. If we declare, for example:
html { font-size:5vw; }
It will tell the browser that 1rem always equals 5% of the window width, so every time we resize the window, the rem unit will update accordingly, resulting in a super dynamic layout.
CSS rem has made our life at W4 a lot easier, and most of the designers we work with love this method. Sometimes, some adjustments need to be made, but overall, it works great.
If this was helpful - remember to like, respond or share! Any questions? Feel free to ask!