Relative units in CSS

CSS relative units are used to specify the size of an element relative to the size of another element in a HTML file. CSS relative units allows...

CSS relative units are used to specify the size of an element relative to the size of another element in a HTML file. CSS relative units allows elements to scale up and down according to the size of other elements.

The rem unit

The rem unit is relative to the root HTML document. The root HTML document is by default 16px. Which means, 1rem equals 16px and 2rem equals 32px. However, the default size of the root HTML document can be changed and doesn't always have to be 16px.

Example:

html {
    font-size: 20px;
}

h2 {
    font-size: 2rem;
}

In the code above, the default size of the root HTML document has been set to 20px. Therefore, the font-size of the h2 element is 20px * 2 which is 40px.

The em unit

em is also a relative unit but differs from rem because its size depends on its parent element and not the root HTML document.

Example:

html {
    font-size: 20px;
}
.parent-container {
    font-size: 15px;
}

.child-element {
    font-size: 3em;
}

In the code above, the default size of the root HTML document has been set to 20px and the size of the parent-container which is the parent element has been set to 15px. Therefore, the font-size of the child-element will be 15px * 3 which equals 45px.

vw(viewport width) and vh(viewport height)

These units are units relative to the width or height of the viewport. The viewport is basically the size of the screen or the browser window. 100vh basically means 100% the height of the browser window which will take up the entire screen and 50vh basically means 50% the height of the browser window which will take up half the entire screen. Same with vw.

%

% is a relative unit. Any element whose size is defined in % is a percentage of the of another element which is usually the parent element. But in certain cases where the parent's size is not defined, the element's size will be a the percentage of the body.

.parent-container {
    Width: 200px;
}

.child-element {
    width: 40%;
}

In the code above, the width of the parent-container which is 200px. Therefore, the width of the child-element will be 40% of 200px which equals 80px.

Conclusion

CSS relative units are perfect for creating scalable layouts which makes creating responsive websites easier.