CSS Basics: Data Types Part 1

A CSS data type = a type of CSS value. Some examples:

  • color: green
  • number: 90
  • length: 10px
  • images
  • gradients

Lengths

Pixel (px) is an absolute length and does not scale regardless of the size of the browser window.

Percentage (%) is a relative length measured against the element's parent's length.

Em, one em is equal to the font-size value of the parent element. To convert px to em, divide px by parent's font-size.

For example:

<body>
  <div class="intro">
  </div>
</body>
body {
  font-size: 16px;
}
.intro {
  font-size: 24px;
}

To convert .intro's px font-size to an em value, .intro's 24px is divided by its parent element, <body>'s, px value. Like so:

Screenshot 2015-11-19 21.43.00.png

Note: there is a compounding effect when nesting elements and using em.

Root em (rem) is similar to em but it is only relative to the root element of the page. The root element is typically the HTML element on a webpage.

So, which one to use?

px is more precise, easier to understand, and predictable while %, em, and rem are more well-suited for designs that need to scale and adapt fluidly across different devices and screen sizes.