How to Set Font-Size in CSS: Simple Guide with Examples
To set font size in CSS, use the
font-size property with a value like 16px, 1.5rem, or 120%. This property controls the size of text in an element and can be applied to any HTML element.Syntax
The font-size property sets the size of the text. You write it inside a CSS rule like this:
selector { font-size: value; }selectoris the HTML element or class you want to style.valueis the size you want, using units like pixels (px), relative units (rem,em), or percentages (%).
css
selector {
font-size: value;
}Example
This example shows how to set the font size of a paragraph to 18 pixels. The text will appear larger than the default size.
html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Font Size Example</title> <style> p { font-size: 18px; } </style> </head> <body> <p>This text is 18 pixels in size.</p> </body> </html>
Output
A webpage showing a paragraph with text 'This text is 18 pixels in size.' in a larger font than default.
Common Pitfalls
Common mistakes when setting font-size include:
- Using no units (e.g.,
font-size: 16;) which is invalid. - Using inconsistent units that confuse users, like mixing
pxandemwithout understanding their differences. - Setting font size too small, making text hard to read.
Always include units and consider accessibility by choosing readable sizes.
css
/* Wrong: missing units */ p { font-size: 16; } /* Right: with units */ p { font-size: 16px; }
Quick Reference
| Unit | Description | Example |
|---|---|---|
| px | Pixels - fixed size | font-size: 16px; |
| rem | Relative to root font size | font-size: 1.5rem; |
| em | Relative to parent element font size | font-size: 1.2em; |
| % | Percentage of parent font size | font-size: 120%; |
| vw | Relative to viewport width | font-size: 5vw; |
Key Takeaways
Always use units like px, rem, em, or % when setting font-size in CSS.
Use relative units like rem or em for better accessibility and responsiveness.
Avoid setting font sizes too small to keep text readable.
The font-size property controls text size for any HTML element.
Test font sizes on different devices to ensure good user experience.