🔠 CSS font-size
: Setting the Perfect Size for Your Text
The size of your text is one of the most important factors affecting readability, accessibility, and the overall feel of your website. The CSS font-size
property allows you to precisely control the size of text on your webpage, from tiny captions to huge headlines.
🧾 What is font-size
?
The font-size
property defines the size of the font used to display text. It affects not only how large the text appears but can also influence line height and spacing.
🧬 Syntax
selector {
font-size: value;
}
Possible values:
Value Type | Examples | Description |
---|---|---|
Absolute units | px , pt , cm , mm , in | Fixed sizes; pixels (px ) are most common |
Relative units | em , rem , % , vw , vh | Relative to parent (em ), root (rem ), viewport, or percent |
Keywords | small , medium , large | Predefined sizes with approximate meanings |
🎯 Examples
1. Using Pixels (px
)
h1 {
font-size: 36px;
}
Sets the heading to exactly 36 pixels high.
2. Using Relative Units (em
)
p {
font-size: 1.2em;
}
Sets the paragraph text to 1.2 times the size of its parent element’s font size.
3. Using Root Relative Units (rem
)
body {
font-size: 16px;
}
h2 {
font-size: 2rem; /* 2 times the root font size (32px) */
}
rem
is relative to the root (html
) font size, providing more consistent scaling.
🧠 How It Works
- Absolute units (
px
) give fixed sizes but can be less flexible on different screens or zoom levels. - Relative units (
em
,rem
) help create responsive, scalable typography. - Keywords like
medium
orsmall
offer easy presets but are less precise. - Browsers have default font sizes (usually 16px), which relative units base their calculations on.
- Using relative units improves accessibility by respecting user preferences for text scaling.
🛠️ Tips & Best Practices
- Prefer
rem
for font sizing to maintain consistency and accessibility. - Avoid using only
px
if you want your site to be more flexible and responsive. - Use media queries with font-size for better readability on various devices.
- Combine with
line-height
for comfortable reading experience. - Test your font sizes on different screen sizes and resolutions.
✅ Browser Support
The font-size
property is supported universally in all browsers and devices.
- ✅ Chrome
- ✅ Firefox
- ✅ Safari
- ✅ Edge
- ✅ Internet Explorer 6+
🔚 Conclusion
Mastering font-size
is key to making your website readable, accessible, and visually balanced. Whether you choose fixed pixels or scalable units, the right font size sets the tone for your content.