learn2kode.in

CSS Units (px, %, em, rem, vw, vh)

CSS uses different types of units to define sizes, spacing, fonts, and layouts. These units can be absolute (fixed) or relative (depending on the parent or viewport).

1. px — Pixels (Absolute Unit)

Example

2. % — Percentage (Relative to Parent)

Example

3. em — Relative to Parent Font Size

Example

.parent { font-size: 20px; }
.child { font-size: 2em; } /* 40px */

4. rem — Relative to Root Font Size (html element)

Example

html { font-size: 16px; }
.box { padding: 2rem; } /* 32px */

5. vw — Viewport Width

Example

6. vh — Viewport Height

Example

.section { height: 100vh; }

HTML Table for CSS Units

Unit Type Description Example
px Absolute Fixed size, does not scale width: 100px;
% Relative Relative to parent size width: 50%;
em Relative Relative to parent font size font-size: 2em;
rem Relative Relative to root (html) font size padding: 1.5rem;
vw Relative 1% of viewport width font-size: 5vw;
vh Relative 1% of viewport height height: 100vh;