css em vs rem

css

In CSS, the em and rem units are used to specify sizes of elements, such as font sizes, margins, and padding.

The em unit is relative to the font size of the element itself. For example, if an element has a font size of 16 pixels and you specify a margin of 1em, the margin will be 16 pixels. If the font size of the element is changed, the value of 1em will also change.

The rem unit, on the other hand, is relative to the root element (usually the html element) of the document. This means that if you specify a font size of 16 pixels for the root element and a margin of 1rem for an element, the margin will be 16 pixels, regardless of the font size of the element itself.

Here’s an example of how you might use the em and rem units in a CSS stylesheet:

html {
    font-size: 16px;
}

body {
    font-size: 1.2em; /* 18.4 pixels */
    margin: 1rem; /* 16 pixels */
}

h1 {
    font-size: 2em; /* 32 pixels */
}

p {
    font-size: 0.8em; /* 12.8 pixels */
    margin: 0.5rem; /* 8 pixels */
}

In this example, the root element (html) has a font size of 16 pixels, so the rem units used in the body and p elements will be 16 pixels. The body element also has a font size of 1.2em, which is 18.4 pixels, and the h1 element has a font size of 2em, which is 32 pixels. The p element has a font size of 0.8em, which is 12.8 pixels, and a margin of 0.5rem, which is 8 pixels.