Units in CSS
Units in CSS Measuring Sizes and Distances
CSS uses various units to specify lengths, sizes, and measurements in styles. These units can be absolute or relative.
1. Absolute Units
Fixed sizes that dont change based on context or screen size.
| Unit | Description | Example |
|---|---|---|
px | Pixels, fixed screen pixels | width: 100px; |
pt | Points, mostly for print (1pt=1/72 inch) | font-size: 12pt; |
cm | Centimeters | margin: 2cm; |
mm | Millimeters | padding: 5mm; |
in | Inches | height: 3in; |
pc | Picas (1pc = 12pt) | border-width: 2pc; |
2. Relative Units
Relative to some other value, which makes them more flexible and responsive.
| Unit | Description | Example |
|---|---|---|
% | Percentage relative to parent element | width: 50%; |
em | Relative to font-size of the element | font-size: 2em; (2 ื current font size) |
rem | Relative to root element's font size (html font size) | margin: 1.5rem; (1.5 ื root font size) |
vw | 1% of viewport width | width: 50vw; |
vh | 1% of viewport height | height: 100vh; |
vmin | Minimum of vw or vh | font-size: 5vmin; |
vmax | Maximum of vw or vh | font-size: 10vmax; |
ch | Width of the 0 character in the font | width: 20ch; |
ex | Height of the lowercase x in the font | Less commonly used |
Which Unit to Use?
Use
pxfor precise control, but not responsive-friendly.Use
%,em, orremfor flexible, scalable layouts.Use viewport units (
vw,vh) for full-screen and responsive designs.Use
remfor font sizes to keep scalability consistent.
Example
body { font-size: 16px; /* Base font size */}h1 { font-size: 2rem; /* 2 ื 16px = 32px */ margin-bottom: 1.5em; /* 1.5 ื current font size */ width: 80%; /* 80% of parent width */}.container { width: 90vw; /* 90% of viewport width */ height: 50vh; /* 50% of viewport height */}Want me to help with a unit converter tool or explain when to use each unit for responsive design?