CSS Measurement Units

CSS provides various units of measurement to specify lengths, sizes, and other dimensions for styling elements. Here are some commonly used units


Absolute Units

Absolute units in CSS are fixed units of measurement that do not change in relation to other elements on the page. They provide a specific and unchanging size regardless of the screen size or parent element.


px (Pixels)

  • Absolute unit based on screen pixels.

  • Provides a fixed-size representation.

Example

/* Setting width and height in pixels */
.box {
  width: 200px;
  height: 150px;
}


in (Inches)

  • Represents inches.

  • Less commonly used for web design due to screen variations.

Example

/* Specifying width in inches */
.print-area {
  width: 2in;
}


cm (Centimeters)

  • Represents centimeters.

  • Similar to inches but using the metric system.

Example

/* Specifying margin in centimeters */
.section {
  margin: 1cm;
}


pt (Points)

  • Commonly used in print, representing 1/72nd of an inch.

  • Useful for specific print-related CSS.

Example

/* Setting font size in points */
.print-header {
  font-size: 12pt;
}


Relative Units

Relative units in CSS are measurements that are relative to other elements or certain properties on the web page. They provide flexibility and responsiveness, adapting to different screen sizes and devices.


% (Percentage)

  • Relative to the size of the parent element.

  • Often used for width, height, margins, and padding.

Example

/* Setting width relative to the parent */
.container {
  width: 80%;
}


em

  • Relative to the font size of the element.

  • Particularly useful for text-related properties like font size.

Example

p {
  font-size: 1.2em; /* Makes the font size 1.2 times the parent element's font size */
}


rem

The rem unit is a relative length unit that represents the font size of the root element (<html>). Unlike the em unit, which is relative to the font size of its parent element, rem is always relative to the font size of the root element.

Example

/* Setting margin relative to the root font size */
.section {
  margin: 1.5rem;
}


vw (Viewport Width) and vh (Viewport Height)

vw and vh are relative length units that represent a percentage of the viewport’s width (vw) or height (vh).

Example

.box {
  width: 50vw; /* Sets the width of the box to 50% of the viewport width */
}

.box {
  height: 80vh; /* Sets the height of the box to 80% of the viewport height */
}