π 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
| Unit | Type | Example |
|---|---|---|
| px | Absolute | 16px |
| em | Relative to parent | 1.5em |
| rem | Relative to root | 2rem |
| % | Relative to parent | 120% |
| vw | Viewport width | 5vw |
Note
π§ 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
Further details can be found at: https://dummyimage.com/800x250/ddd/000&text=Font-Size+Demo
π 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.
π 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. π