DEV Community

Cover image for CSS Tips: Relative units with EM and REM
Mateus V. Farias
Mateus V. Farias

Posted on • Edited on

CSS Tips: Relative units with EM and REM

We have already seen the use of the relative unit of measure with %. We use this relative measure when we want an element to use, for example, 100% of the available space.

HTML:

<div>
  <img src="img/avatar.png" alt="Avatar">
</div>
Enter fullscreen mode Exit fullscreen mode

CSS:

div {
  width: 400px;
}
Enter fullscreen mode Exit fullscreen mode

In the example above, depending on the size of the image, the image may exceed the space we defined for the <div> or it may occupy a smaller space. If we want the image to occupy the entire space of the <div>, we can use the relative unit %:

div {
  width: 400px;
}

img {
  width: 100%; /* It occupies 100% of the available space */
}
Enter fullscreen mode Exit fullscreen mode

The great advantage of using % is that no matter what size we put in <div>, <img> will always follow the size of its parent tag (the <div>).

EM and REM have the same concept as %, but instead of being based on the size of an element, these measures are based on the size of the font. EM uses the font size of the parent element and REM uses the font size of <html>.

HTML:

<html>
<head>
    <meta charset="UTF-8">
    <title>An example</title>
</head>
<body>
    <div>
        <img src="img/avatar.png" alt="Avatar">
    </div>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

CSS:

html {
  font-size: 10px;
}

div {
  font-size: 20px;
}

img {
  width: 10em; /* The width will be 200px */
  height: 10rem; /* The height will be 100px */
}
Enter fullscreen mode Exit fullscreen mode

The advantage of using these measures is that if we have other elements using these measures and we need to change the size of all the elements proportionately, just change them in one place. These units of measure are ideal for when the website needs to be displayed on different screen sizes, where on each screen size the font must be displayed on different size scales and proportional to each other.

Top comments (4)

Collapse
 
nicozerpa profile image
Nico Zerpa (he/him)

When it comes to font sizes, "rem" units are very useful for accessibility. Some people with vision problems increase the default font size in their browser settings to read texts better.

However, this doesn't affect texts that have their size set in px. If you use em for font sizes, the text will adjust to the browser settings and everybody will be able to read the content.

Collapse
 
fariasmateuss profile image
Mateus V. Farias

Awesome 🀩

Collapse
 
aminmansuri profile image
hidden_dude

For fonts is it better to use pixels or points?
I've always use pt instead of px because that's the common font measure.

Collapse
 
fariasmateuss profile image
Mateus V. Farias

Use EM, REM or PX πŸ˜‰.