CSS Tutorial

Units in CSS

Understanding units in CSS is crucial for creating responsive and accessible web designs. Here's a quick guide to the most commonly used units:

  • Pixels (px):
    • Absolute unit representing a fixed number of physical pixels on the screen.
    • Ideal for specifying exact sizes for elements (e.g., icons, images).
  • Ems (em):
    • Relative unit based on the font size of the parent element.
    • Useful for setting font sizes and spacings that scale with the base font.
  • Rems (rem):
    • Similar to ems, but based on the root font size of the document.
    • Ensures consistency across the entire document, regardless of nested elements.
  • Percentages (%):
    • Relative unit that specifies a value relative to the containing element.
    • Ideal for setting sizes and positions that adapt to different screen sizes.
  • Viewport units (vw, vh, vmin, vmax):
    • Units based on the viewport dimensions.
    • Useful for creating elements that scale proportionally to the viewport.
  • Other units:
    • Inches (in), Centimeters (cm), Millimeters (mm): Absolute units representing physical measurements.
    • Picas (pc), Points (pt): Units used in typography and design.

Example:

body {
  font-size: 16px; /* Sets the base font size for the document */
}

p {
  margin: 1em; /* Sets a margin of 1em (based on the base font size) */
  font-size: 1.5rem; /* Sets a font size of 1.5rem (based on the document's root font size) */
  width: 50vw; /* Sets the width of the paragraph to 50% of the viewport width */
}

Accessibility considerations:

  • Use relative units (ems, rems, percentages) whenever possible to ensure accessibility for users who need to adjust font size.
  • Avoid using absolute units (pixels) for font sizes, as they may not scale properly for users with different screen resolutions.