CSS Units - Detailed Overview

Introduction to CSS Units

CSS provides various units for defining sizes, lengths, and dimensions. These units can be relative or absolute and each serves different purposes in layout and design.

Examples of CSS Units

Below are examples of different CSS units used for sizing elements:

.pixels {
    background-color: #f00;
    width: 100px;
    height: 100px;
}

.percent {
    background-color: #0f0;
    width: 50%;
    height: 100px;
}

.em {
    background-color: #00f;
    width: 10em;
    height: 10em;
}

.rem {
    background-color: #ff0;
    width: 10rem;
    height: 10rem;
}

.vh {
    background-color: #f0f;
    width: 50vw;
    height: 50vh;
}

.vw {
    background-color: #0ff;
    width: 50vw;
    height: 50vw;
}

.ch {
    background-color: #ff6;
    width: 20ch;
    height: 5em;
}

.vmin {
    background-color: #0f6;
    width: 20vmin;
    height: 20vmin;
}

.vmax {
    background-color: #6f0;
    width: 20vmax;
    height: 20vmax;
}

Pixel (px)

Width and height are set using pixels (px).

Percentage (%)

Width is set to 50% of the parent element.

Em (em)

Width and height are set using ems (relative to font-size).

Rem (rem)

Width and height are set using rems (relative to root font-size).

Viewport Height (vh)

Width is set to 50% of the viewport width and height to 50% of viewport height.

Viewport Width (vw)

Width and height are set relative to viewport width.

Character (ch)

Width is set relative to the width of the "0" character in the current font.

Viewport Minimum (vmin)

Width and height are set to 20% of the viewport's smaller dimension.

Viewport Maximum (vmax)

Width and height are set to 20% of the viewport's larger dimension.