CSS Units
Many CSS properties, like width, margin and font-size, need a number with a unit. There are two kinds of units: absolute and relative.
Absolute unit: px
A pixel (px) is a fixed size. It does not change when the screen or the parent changes. Other absolute units are pt, cm and in, which are mostly used for printing.
Relative units
| Unit | Relative to | Example |
|---|---|---|
% | The size of the parent element | width: 50% |
em | The font size of the element (or of its parent for font-size) | padding: 2em |
rem | The font size of the root (html) element | font-size: 1.5rem |
vw | 1% of the viewport width | width: 80vw |
vh | 1% of the viewport height | height: 100vh |
html { font-size: 16px; }
h1 { font-size: 2rem; } /* 2 x 16 = 32px */
p { font-size: 1.125rem; } /* 18px */
.box { width: 50%; padding: 1em; }
Which unit should I use?
- Font sizes:
rem, so the text follows the visitor’s own font settings. - Widths:
%ormax-widthwith a px value, so layouts can shrink. - Full screen sections:
vhandvw. - Borders and thin lines:
px.
Note:
A value of 0 needs no unit. Write margin: 0 and not margin: 0px.
Summary
pxis fixed.%,em,rem,vwandvhare relative.- Use
remfor fonts and%ormax-widthfor flexible layouts. - Next: CSS Background.
Congratulations! Chapter Finished. Learn more about the similar topics:
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |