0
0
CssHow-ToBeginner · 3 min read

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; }
  • selector is the HTML element or class you want to style.
  • value is 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 px and em without 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

UnitDescriptionExample
pxPixels - fixed sizefont-size: 16px;
remRelative to root font sizefont-size: 1.5rem;
emRelative to parent element font sizefont-size: 1.2em;
%Percentage of parent font sizefont-size: 120%;
vwRelative to viewport widthfont-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.