I’m trying to build a responsive page using rem unit for the first time. I have my root html font-size set to 16 px and I have set container width 80 rem.
html {
font-size: 16px;
}
.container {
width: 80rem;
}
My understanding is that 80rem should be 80 * 16px = 1280px.
But when I resize the browser the container width stays fixed at 1280px and doesn’t scale down responsively.
What am I missing here? I thought using pixel font-size on html was the right approach for responsive scaling with rem?
2
Answers
The
font-size: 16px
doesn’t change when you resize the browser, hence the container width is always equal to1280px
.If you want to change the container width based on browser resize, then you need to use
vw
which is based on viewport.Below is how you can have your container element to be always 80% of viewport.
if you still want to use rem then you need to change the root font-size based on browser resize.
REM is a relative unit to the root aka
<html>
tag. So if you set thefont-size:16px
in.html
and givefont-size:1rem
to.p
then size of text in<p>
would be equivalent to16px
.REM helps create responsive pages easily as you can adjust the size of every element on the page by changing just the font-size in root element. Though, you still have to use the media queries to set font-size of
<html>
for different viewports.REM also helps you create pages with better accessibility features. For instance, you can add a slider on the web page that adjusts the root font size and in turn makes the design, fonts, everything bigger to make it easy to see/read for visually impaired people.
So, this is how REM works. Below is the code for your information:
Answering your follow up question:
I understand it is a bit mind bogging, especially when you are just starting to give sizes in em/rem in CSS. But with time you’ll learn it.
Now that you have the web page ready with all sizes in px, below are few ways you can change and convert all px values to rem.
Easiest way for you: You can install vscode plugin called pixel to rem (https://marketplace.visualstudio.com/items?itemName=sainoba.px-to-rem) which lets you easily select and convert values by pressing alt+z
Easy but a bit time consuming way: You can use online px to rem converters (https://cssunitconverter.com/px-to-rem/) and copy paste the values.
Advanced but a fun and learning way: Using Sass, create a px-to-rem mixin that handles the conversion based on a $root-font-size variable (tutorial – https://dev.to/nikolab/convert-px-to-rem-using-sass-3-methods-4ep2).