CSS Unit of Measurement


In CSS, absolute and relative units are used to specify measurements, but they function differently and are used in different contexts. Here’s a breakdown of their differences:

Absolute Units

Absolute units are fixed and do not change with respect to other elements or the viewport. They are based on physical measurements or fixed sizes.

Unit

Description

px

Pixels: based on the screen resolution, typically used for precise control

pt

Points: commonly used in print stylesheets, where 1pt = 1/72 of an inch

in

Inches: physical unit of measurement, 1 inch

cm

Centimeters: physical unit of measurement, 1 centimeter

mm

Millimeters: physical unit of measurement, 1 millimeter

pc

Picas: commonly used in print media, where 1pc = 12pt

Example:

div {
    width: 300px;  /* Always 300 pixels wide */
}


Relative Units

Relative units are flexible and change based on the context, such as the size of a parent element, the viewport, or the root font size. They are useful for creating responsive designs.

Unit

Description

%

Percentage: relative to the parent element’s size

em

Em: relative to the font size of the element (2em means 2 times the size of the current font)

rem

Rem: relative to the font size of the root element (html element)

vw

Viewport Width: 1vw is equal to 1% of the viewport’s width

vh

Viewport Height: 1vh is equal to 1% of the viewport’s height

vmin

Viewport Minimum: 1vmin is equal to 1% of the smaller dimension of the viewport

vmax

Viewport Maximum: 1vmax is equal to 1% of the larger dimension of the viewport

ex

Ex: relative to the x-height of the current font (rarely used)

ch

Ch: relative to the width of the “0” (zero) character in the current font

fr

Fraction: used in CSS Grid Layout to define a fraction of the available space

Example:

div {
    width: 50%;  /* 50% of the parent element’s width */
}

p {
    font-size: 2em;  /* 2 times the font size of the element */
}

.container {
    width: 50vw;  /* 50% of the viewport’s width */
}

Key Differences

  1. Fixed vs. Flexible:
    • Absolute units provide a fixed measurement.
    • Relative units provide a flexible measurement that adapts based on the context.
  2. Use Cases:
    • Absolute units are useful when you need precise control over element dimensions, regardless of the parent or viewport size.
    • Relative units are ideal for responsive designs, where elements need to scale relative to other elements, the viewport, or the root font size.
  3. Responsiveness:
    • Absolute units do not change with screen size or parent element dimensions.
    • Relative units adjust based on the dimensions of the parent element, the root font size, or the viewport size, making them more suitable for responsive design.

Understanding when to use absolute vs. relative units is key to creating effective, responsive web designs.

Scroll to Top