font-size

The font-size property in CSS is used to specify the size of the font for an element.

Basic Usage

You can set the font size using various units, keywords, or percentages:

/* Using pixels */
p {
  font-size: 16px;
}

/* Using em units (relative to parent font size) */
h1 {
  font-size: 2em;
}

/* Using relative keywords */
body {
  font-size: medium;
}

Available Units and Keywords

  • Absolute units:
    • px: Pixels
    • cm: Centimeters
    • mm: Millimeters
    • in: Inches
    • pt: Points
    • pc: Picas
  • Relative units:
    • em: Relative to the font size of the parent element
    • rem: Relative to the font size of the root element (html)
    • %: Relative to the font size of the parent element
    • vw: Relative to the viewport width (1vw = 1% of viewport width)
    • vh: Relative to the viewport height (1vh = 1% of viewport height)
    • vmin: Relative to the smaller of vw or vh
    • vmax: Relative to the larger of vw or vh
  • Keywords:
    • xx-small
    • x-small
    • small
    • medium
    • large
    • x-large
    • xx-large
    • larger
    • smaller

Example with Different Units

html {
  font-size: 16px; /* Base font size */
}

body {
  font-size: 1.2rem; /* 19.2px */
}

h1 {
  font-size: 2.5em; /* Relative to parent (body) */
}

p {
  font-size: 18px;
}

.small-text {
  font-size: 0.8em; /* Relative to parent */
}

Important Considerations

  • Base font size: It’s recommended to set a base font size for the html element to establish a consistent baseline for your typography.
  • Relative units: Using em and rem units can create flexible and responsive designs.
  • Viewport units: vw, vh, vmin, and vmax are useful for creating designs that adapt to different screen sizes.
  • Browser compatibility: Be aware of browser compatibility when using different units and keywords.

Additional Tips

  • Use a consistent font size scale for better readability and hierarchy.
  • Consider using CSS preprocessors (like Sass or Less) for easier management of font sizes.
  • Test your designs on different devices and screen sizes to ensure optimal display.

By understanding these concepts and experimenting with different values, you can effectively control the font size in your CSS and create visually appealing designs.