CSS Units
CSS Units are used to define sizes, lengths, and dimensions in CSS properties. Understanding these units is crucial for creating responsive and adaptable designs. CSS provides several types of units, each serving different purposes.
Types of CSS Units
1. Absolute Units
Absolute units are fixed and do not change with the viewport size. They are useful for precise measurements but may not be as flexible for responsive designs.
- Pixels (px): Represents a fixed number of pixels. Commonly used for precise control over dimensions.
- Points (pt): Typically used in print media. 1pt is 1/72 of an inch.
- Inches (in): Represents a physical inch. 1in = 96px (approximate).
- Centimeters (cm): Represents a physical centimeter. 1cm = 96px/2.54.
- Millimeters (mm): Represents a physical millimeter. 1mm = 96px/25.4.
/* Absolute Units */
.fixed-width {
width: 300px; /* 300 pixels */
}
.print-header {
font-size: 12pt; /* 12 points */
}
This element has a fixed width of 300px.
2. Relative Units
Relative units adjust based on the size of the parent or root element. They are ideal for creating responsive designs.
- Percentage (%): Relative to the parent element’s size. Useful for fluid layouts.
- Em (em): Relative to the font size of the parent element. Commonly used for scalable text.
- Rem (rem): Relative to the font size of the root element (`html`). Consistent across the page.
- Viewport Width (vw): Relative to 1% of the viewport’s width. Useful for full-width elements.
- Viewport Height (vh): Relative to 1% of the viewport’s height. Useful for height adjustments.
- Vmin and Vmax: Relative to the smaller or larger value of viewport width and height, respectively.
/* Relative Units */
.relative-width {
width: 50%; /* 50% of parent width */
}
.scalable-text {
font-size: 1.5em; /* 1.5 times the parent font size */
}
.root-font-size {
font-size: 1rem; /* Relative to the root font size */
}
.full-width {
width: 100vw; /* 100% of viewport width */
}
.full-height {
height: 100vh; /* 100% of viewport height */
}
This element is 50% of its parent width.
This text scales with the font size of the parent.
This element takes up the full viewport width.
This element takes up the full viewport height.