πŸ”  Mastering font-size in CSS

πŸ“Œ Introduction

The font-size property in CSS controls how large or small text appears on a webpage. It plays a crucial role in readability, hierarchy, and responsive design. Learning how to use it effectively helps you create clean and accessible UI. ✨

πŸ” What is font-size?

The font-size property sets the size of the text. You can define it using different units like px, em, rem, %, and more.

Basic Usage

p {
  font-size: 16px;
}

πŸ“ Common Units for Font Size

  • πŸ“˜ px β€” Absolute size. Fixed and doesn’t scale with user settings.
  • πŸ“— em β€” Relative to the parent element’s font-size.
  • πŸ“™ rem β€” Relative to the root HTML element’s font-size.
  • πŸ“• % β€” Relative to the parent’s font-size.
  • πŸ“š vw/vh β€” Scales based on viewport dimensions.

πŸ“Š Comparison Table

UnitTypeExample
pxAbsolute16px
emRelative to parent1.5em
remRelative to root2rem
%Relative to parent120%
vwViewport width5vw

Note

πŸ’‘ rem is preferred for accessibility because users’ browser font-size settings still work correctly.

🧠 How em and rem Work

πŸ”Έ Using em

1em equals the font-size of the parent element. If a parent sets font-size: 20px, then 1em = 20px.

EM Example

.parent {
  font-size: 20px;
}

.child {
  font-size: 1.5em; /* 30px */
}
πŸ”Έ Using rem

1rem equals the font-size of the root element (html). Most browsers set html { font-size: 16px } by default.

REM Example

html {
  font-size: 16px;
}

p {
  font-size: 2rem; /* 32px */
}

πŸ”₯ Responsive Font Sizing

To make text automatically adjust based on screen size, you can use:vw units, clamp(), or media queries.

Viewport-Based Font Size

h1 {
  font-size: 5vw;
}

Using clamp() for Better Responsive Control

h1 {
  font-size: clamp(1.5rem, 3vw, 3rem);
}

Note

πŸ’‘ clamp() sets a minimum size, a preferred fluid size, and a maximum sizeβ€”best for modern responsive UIs.

πŸ‘€ Visual Example

πŸ›  Real-World Example

Heading & Paragraph Sizes

h1 {
  font-size: 2.5rem;
}

h2 {
  font-size: 1.75rem;
}

p {
  font-size: 1rem;
}

small {
  font-size: 0.875rem;
}

πŸ’‘ Best Practices

  • βœ”οΈ Prefer rem for consistent scaling.
  • βœ”οΈ Use clamp() for responsive typography.
  • βœ”οΈ Avoid mixing too many different units.
  • βœ”οΈ Test font sizes across devices for readability.
  • βœ”οΈ Keep body text between 15px–18px for comfort.
>>β€œGood typography is invisible. Bad typography is everywhere.”

🏁 Conclusion

Understanding font-size and its units helps you create clean, consistent, and scalable typography across your website. With relative units, responsive techniques, and best practices, your UI becomes both beautiful and accessible. πŸŽ‰