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>
CSS:
div {
width: 400px;
}
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 */
}
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>
CSS:
html {
font-size: 10px;
}
div {
font-size: 20px;
}
img {
width: 10em; /* The width will be 200px */
height: 10rem; /* The height will be 100px */
}
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)
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.
Awesome 🤩
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.
Use EM, REM or PX 😉.