Categories
CSS Tutorials

Size and Other Units of Measurement

Many CSS properties use predefined keywords, but sizes, colors need to be specified individually. This topic describes the units of measurement and the syntax used to specify sizes and colors.

In CSS, some values can be expressed as one of the following forms:

  • Length
  • example: width: 30px;
  • Percentage
  • example: height: 30%;
  • color code
  • example: background-color: #334455;

The CSS specifications use the term length to refer to vertical and horizontal measurements.

Length must be expressed along with units.Length units are classified as either relative or absolute. A relative unit is not a fixed size, but is relative to another length. The relative units in the above table take their value from the current font size. But CSS3 introduces units that are relative to the browser viewport. 

Absolute unit ‘px’

An absolute unit is anchored to a physical measurement, such as an inch or centimeter.

Syntax:

There must be no space between the number (which can include a decimal fraction) and the unit. The unit of measurement is optional after 0. 

For example, the following values are correct:

0.5em

300px

0px

0

The last two examples, 0px and 0, mean the same. Most experienced designers omit the px (or other length unit) but it’s perfectly valid to include it. 

The following examples are incorrect and will not work:

0.5 em

300 px

0 px

Although no unit is required after zero, browsers are likely to interpret the px in the final example as garbage and ignore the style definition.

Relative unit ‘em’

An em is a unit of measurement borrowed from typography. The name originates from the width of the letter M; but in CSS it means the height of the current font, usually including whitespace above and below. So, with a 16-pixel font, one em equals 16 pixels; with a 24-pixel font, it’s 24 pixels, and so on. Specifying the width or height of an element in ems adjusts its size in proportion to the size of the font. Using em to specify font size can result in ever shrinking text because nested elements inherit the size from their parents, resulting in a multiplier effect. for example, if you set the font size of unordered lists to 0.75em (the equivalent of 12px), the text in a nested list is 0.75 times the size of its parent—in other words, 9px. At the next level, the text shrinks even further.

To avoid this multiplier effect with em, you need to reset the size for nested lists to 1em like this:

ul {
   font-size: 0.75em;
}
ul ul {
   font-size: 1em;
}

This sets the text in the nested lists to the same size as the previous list, thereby preventing it from shrinking

Relative unit ‘%’

Percentage is similar to em. 200% simply means 2 times the current font size.

Hence, 200% = 2em. for font.