How to use css rem units for responsive pages

CSS has many units of measurement, some absolute (px) and some relative (rem). Here's how to use rem to make your page responsive.

What is the rem unit?

It stands for "root em" and is a relative unit based on the font size of the "root element" and by root element we mean the <html> element.

How does it work?

Most browsers set the default font-size of the html element to 16px. So if you set any CSS property to 1rem it is the equivalent of making 16px.

Let's see an example, let's set the font-size to 10px in the html element (the root element)

html {
    font-size: 10px;
}

h1 {
    font-size: 4rem; /* 10 * 4 = 40px */
}

main {
    width: 60rem; /* 60 * 10 = 600px  */
}

If we put 10px in our root element, 2rem equals 20px, 7rem equals 70px and so on.

What's the point?

Using rem in all units of your CSS allows you to increase the size of your page (either by layout change or screen size) by simply increasing or decreasing the font-size in the html element.

Increasing the size of your page to take advantage of the most available space is to offer your users a better visual experience and accessibility to your page.

html {
    font-size: 16px;
}

@media only screen and (min-width: 720px) {
    html {
        font-size: 18px;
    }
}

@media only screen and (min-width: 960px) {
    html {
        font-size: 20px;
    }
}

@media only screen and (min-width: 1240px) {
    html {
        font-size: 24px;
    }
}

h1 {
    font-size: 3.5rem; /* 56px, 63px, 70px o 84px */
}

h2 {
    font-size: 2.5rem; /* 40px, 45px, 50px, 60px */
}

h3 {
    font-size: 2rem; /* 32px, 36px, 40px, 48px */
}

Using media queries we can increase or decrease the font-size of the html. Then use rem in the font-size and width to make better use of the available space on the screen.

Full demo

Conclusion

CSS gives us many tools to make our pages responsive but rem is one of the most important as it allows you to scale your page relatively to the single html (root) element of the page.

Copyright © 2024. Design and code by myself with Next.js. Fork it and create yours