CSS Units


CSS uses a variety of units to express length and measurement. CSS units are required to specify measurements in stylesheets, such as padding:"5px." In CSS, there are two types of units.

  • Absolute Length
  • Relative Length

1. Absolute Length:

It is not suitable for use on-screen because screen size varies so greatly depending on the device used for that page; instead, it is best suited for print layout and where the output medium is known.

Example

Preview

Absolute Length Units

Units Description Syntax
cm centimeter font-size: .75cm;
mm millimeter font-size: 6mm;
in inches (1in = 96px = 2.54cm) font-size: .25in;
px pixels (1px = 1/96th of 1in) font-size: 18px;
pt points (1pt = 1/72 of 1in) font-size: 12pt;
pc picas (1pc = 12 pt) font-size: .75pc;

Relative Length:

It is suitable for use on-screen; if the screen size varies greatly depending on the device, these relative length units are ideal because it varies with different rendering mediums.

Example

Preview

Relative Length Units

Units Description Syntax
em Relative to the font size of that element. font-size: 2em;
ex Relative to the X(axis)-height of the current font. font-size: 4ex;
ch Relative to the width of the 0. font-size: 5ch;
rem Relative to the browser base font-size. font-size: 2rem;
vw Relative to 1% of the width of the viewport. font-size: 4vw;
vh Relative to 1% of the height of the viewport. font-size: 4vh;
vmin Relative to 1% of the viewport’s smaller dimension. font-size: 3vmin;
vmax Relative to 1% of the viewport’s larger dimension. font-size: 2vmax;
% % unit sets the font-size relative to the current font-size. font-size: 75%;

FAQs

There are several online tools and calculators that can be used to convert between different CSS units. In general, the conversion formula involves multiplying or dividing the original value by a conversion factor. For example, to convert 16px to em, you would divide by the font size of the parent element (e.g., 16px / 12px = 1.33em).

CSS units can be used for a variety of purposes, such as setting the size of text and images, specifying the width and height of elements, and defining margins and padding. They can also be used for responsive design, where relative units can be used to create flexible layouts that adapt to different screen sizes and resolutions.

The main difference between absolute and relative units is how they are calculated. Absolute units are fixed in size and do not change based on other factors, while relative units are relative to other values and can change based on various factors.