CSS Units
CSS units define the measurement used for properties like width, height, padding, font-size, margin, etc.
There are two main types:
1. Absolute Units (Fixed Size)
These donโt change based on screen or user settings.
| Unit | Description | Example |
|---|---|---|
px | Pixels (most common) | font-size: 16px; |
pt | Points (print) | 12pt |
cm, mm, in | Physical lengths (rarely used in web) | 2cm, 1in |
โ
Use px when you want a fixed size across all devices.
2. Relative Units (Flexible, Responsive)
These adapt to screen size, font size, and other factors.
| Unit | Relative To | Example |
|---|---|---|
% | Parent element size | width: 80%; |
em | Font size of current element | padding: 2em; |
rem | Font size of root <html> | font-size: 1.5rem; |
vw | 1% of viewport width | width: 50vw; |
vh | 1% of viewport height | height: 100vh; |
๐ em vs rem
1em= 100% of the current elementโs font size.1rem= 100% of the root (html) font size (more consistent).
Example:
html {
font-size: 16px;
}
p {
font-size: 1.5rem; /* 24px */
}๐ Example with Units
.container {
width: 80%; /* responsive */
max-width: 1200px; /* limit */
padding: 2rem;
font-size: 1.2em;
height: 100vh;
}๐ง Best Practices
- Use
%,vw, andvhfor layouts and responsiveness. - Use
remfor scalable and consistent typography. - Avoid
pt,cm,inunless for print styles.
