By using this site you agree to the use of cookies and related technologies.

Learn more

Length units in HTML and CSS

How to use the different units of measurement in HTML and CSS.

Created: 2016-09-30 18:07

Just as in real life, we also have length units in HTML and CSS to help us position elements, and to help us define their width and height. This, and more, can be done using the units listed in the below table:

Pixels (px) One unit of px equals one dot on the screen. Since browsers implemented "page zoom" it is not nearly as bad to use pixels as it was in the past.
Ems (em) 1em equals 16px, depending on the parent elements font-size. We suggest setting a default font-size on the body element to better control what 1em corresponds with.
Exes (ex) One "ex" equals the size of "X", (similar to em's "M").
Percentages (%) Ideal for flexible and fluid layouts, it's often a good idea to declare a minimum and max-width in pixels.
Inches (in) Best suited for Print-Media Types.
Centimeter (cm) Best suited for Print-Media Types.
Millimeter Best suited for Print-Media Types.

Pixels are ideal in situations that demands pixel-precision. Usually when you are working with a lot of raster graphics, or image backgrounds. This is not as bad as some designers want to make it, but you may still want to consider using CSS media queries to design for a variety of screen resolutions.

To create a layout that automatically fits the screen resolution, a combination of percentages and EMs will often be the best choice.

Using the length units

body {
/* Sets the font-size for all text */
  font-size: 0.8em; 
div {
/* Sets the min/max width of a division */
  width: 100%;
  min-width: 900px;
  max-width: 1600px;

Note. The above are just examples, you would most likely need additional code, depending on the layout you are trying to make.