CSS Units - W3Schools

CSS Units ❮ Previous Next ❯

CSS Units

CSS has several different units for expressing a length.

Many CSS properties take "length" values, such as width, margin, padding, font-size, etc.

Example

Set different length values with px and em:

h1 { font-size: 60px;}p { font-size: 1.5em; line-height: 2em;}

Try it Yourself »

The length value is a number followed by a length unit, such as px, em, rem, etc.

Note: A whitespace cannot appear between the number and the unit. However, if the value is 0, the unit can be omitted.

Two Types of Length Units

CSS has two types of length units:

  • Absolute units - Fixed sizes that do not change
  • Relative units - Sizes relative to another length (parent, root, or viewport)

Absolute Units

Absolute units are fixed, and the length expressed in any of these will appear exactly that size.

The most used absolute unit is px (pixels).

Absolute units are not recommended for screens, because screen sizes vary so much. However, they can be used if the output medium is known, such as for print layout.

Unit Description
px pixels (1px = 1/96th of 1in)
pt points (1pt = 1/72 of 1in)
cm, mm, in, pc centimeters, millimeters, inches, picas

Learn more about Absolute Units »

Relative Units

Relative units specify a length relative to another length (like parent element, root element, or viewport).

Relative length units scale better between different screen sizes, making them ideal for responsive web design.

Unit Description
em Relative to the font-size of the parent element
rem Relative to the font-size of the root element
vw, vh Relative to 1% of the viewport width/height
% Relative to the size of the parent element

Tip: The em and rem units are perfect for creating scalable and responsive websites!

Learn more about Relative Units »

❮ Previous Next ❯ +1 Sign in to track progress

Từ khóa » Html Px Alternative