Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
July 14, 2021 09:10 am GMT

Relative Units In CSS

There are two important relative units in CSS called, em and rem.

em

It is a sizing unit. It works w.r.t parent node/div.
1em is generally 16px (pixels).

Example:

<div class="parent">    <div class="child">        <div class="second_child">            Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laboriosam cumque ratione provident totam soluta, fugiat obcaecati sequi incidunt magnam esse architecto officia, enim tempore minima asperiores? Labore ab error dolores, numquam, quas magnam atque commodi doloribus aperiam maxime consequatur temporibus eos.        </div>    </div></div>CSS -.parent {    font-size: 16px;}.child {    font-size: 2em;}.second_child {    font-size: 3em;}

Suppose the font size of a parent div is set as 16px and the font size of a child div is set as 2em. This generally means that the text inside child div will have font size of 16*2 px i.e 32px.
Now, let's assume that we have set the font size of a second child as 3em, this means that the text content inside second_child will have font size of 16*2*3 px i.e 96px.

In this scenario, when we use em as a unit to define font size then the size is defined w.r.t the parent node. This is called as compounding in CSS.

If there isn't any parent div then 1em will be considered as 16px only.

Codepen -

rem

rem stands for root em. It solves compounding problem of em. rem doesn't work w.r.t parent node instead it always works w.r.t root node i.e html or ::root.

rem is more consistent than em.

For consistent spacing, margin, padding and font-size always use rem.

Example:

::root {    font-size: 16px;}orhtml {    font-size: 16px;}.parent {    font-size: 50px;}.child {    font-size: 2rem;}.second_child {    font-size: 3rem;}

In the above example, the font size of a child div is set to 2rem which is 32px in case of rem because we have defined font size as 16px in root. rem unit isn't dependent upon parent instead it works w.r.t the root or html node.

Here, in root we have defined the font size as 16px hence font size of a child div is 16*2 px i.e 32px. Similarly, the font size of a second_child will be 16*3 px i.e 48px.

The parent div does not influence anything inside children divs in case of rem units.

Codepen -

Helpful tip - While defining a font size avoid using em as much as possible. Use it only when it is necessary. To maintain the consistency, use rem unit.


Original Link: https://dev.to/vivekalhat/relative-units-in-css-7n

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To