Skip to main content

How to Change the Font Size in CSS

· 3 min read
Jagdish Kumawat
Founder @ Dewiride

font-size sets how big the text is. Give it a size with a unit: pixels, px, for a fixed size, or rem for a size relative to the page's base size of 16 pixels.

Syntax​

Syntax
<selector> {
font-size: <size>;
}
PartWhat it does
<selector>The text to resize.
<size>A number with a unit: 40px for 40 pixels, or 1.25rem for 1.25 times the root size. The unit is required.

MDN's font-size page explains every unit, and that rem values are relative to the root html element.

The Example​

The example is a page of opening hours with a 40-pixel heading and a paragraph at 1.25rem.

Step 1: Write the Code​

Create a file named index.html in a text editor, such as Visual Studio Code:

index.html, an HTML page with a style element holding a rule for h1 with a font-size of 40px and a rule for p with a font-size of 1.25rem, and a body with the heading Opening hours and one paragraph.

index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Font size</title>
<style>
h1 {
font-size: 40px;
}

p {
font-size: 1.25rem;
}
</style>
</head>
<body>
<h1>Opening hours</h1>
<p>Monday to Friday, 9:00 to 17:00.</p>
</body>
</html>

Step 2: Open It in a Browser​

Double-click index.html. It opens in your browser:

The page in Chromium: a large heading Opening hours and the paragraph Monday to Friday, 9:00 to 17:00. in text a little bigger than normal.

The screenshot comes from Chromium 159, the open-source browser that Chrome is built on.

What Happened​

  • The heading is 40 pixels, exactly as set.
  • The paragraph is 20 pixels. The root html element was 16 pixels, and 1.25rem is 1.25 times that.

Common Mistakes​

MistakeWhat happensDo this instead
Leaving out the unit: font-size: 20The value is invalid and ignored: the text stayed 16 pixelsAdd the unit: 20px
Using em inside elements that also use emem is relative to the parent's size, so it compounds: 1.5em inside 1.5em gave 24 pixels, then 36Use rem

Troubleshooting​

SymptomLikely causeFix
The size doesn't changeThe unit is missingAdd px or rem
Nested text gets bigger and biggerem sizes multiply at each levelSwitch to rem

FAQ​

What's the difference between rem and em?​

rem is relative to the root html element, so 1.5rem is the same size everywhere. em is relative to the parent's size, and MDN's page calls the growth that causes compounding.

How big is the text by default?​

16 pixels in Chromium: that's what the root html element and a paragraph without a font-size measured.

Conclusion​

Give font-size a number with a unit. Use px for a fixed size, and rem for sizes that scale with the root size without compounding.

Additional Resources​