Sobes.tech
Middle+

What are the units of measurement rem, em, vw, vh in CSS? How do they differ and how do they work?

sobes.tech AI

Answer from AI

In CSS, measurement units rem, em, vw, and vh are used to specify sizes but differ in context:

  • em — a relative unit equal to the font size of the parent element. For example, if the parent has a font size of 16px, then 1em = 16px.
  • rem — a relative unit equal to the font size of the root element (<html>). Regardless of nesting, 1rem is always the same.
  • vw — 1% of the viewport width. For example, 10vw = 10% of the browser window's width.
  • vh — 1% of the viewport height.

Differences:

  • em depends on the parent, rem depends on the root of the document.
  • vw and vh depend on the size of the browser window, not on fonts.

Example:

.element {
  font-size: 2em; /* twice the size of the parent's font */
  margin-top: 5vh; /* 5% of the viewport height as margin */
}