Skip to content

Difference between px vs em vs rem in CSS

Published: at 08:44 AM (3 min read)

px, em, and rem are units of measurement used in web development to define the size of elements such as text, margins, padding, and other layout properties. Here’s the difference between them:

Pixels (px):

Example: Suppose you set a heading’s font size to 24px. It will always appear as 24 pixels tall, regardless of the screen size or the container it is placed in.

Relative units:

Relative units are used to create more flexible and scalable designs that adapt to different screen sizes and contexts. They adjust based on the surrounding elements.

a. EM (em):

Example: Let’s say you have a paragraph with a font size of 16px, and inside that paragraph, you have a span with a font size of 1.5em. If the parent paragraph’s font size is 16px, the span’s font size will be 1.5 times the parent’s font size, resulting in 24px (16px * 1.5 = 24px).

b. REM (rem):

Example: If the root (html) element’s font size is set to 16px, and you have a heading with a font size of 2rem, it will be calculated as 2 times the root’s font size, resulting in 32px (16px * 2 = 32px).

<div class="container">
  <h1>Heading</h1>
  <p>Paragraph with <span>some text</span>.</p>
</div>
.container {
  font-size: 16px;
}

h1 {
  font-size: 24px; /* Using pixels (px) */
  margin-bottom: 1em; /* Using em */
}

p {
  font-size: 1.5rem; /* Using rem */
}

span {
  font-size: 1.2em; /* Using em */
}

CodePen Link