CSS Font Size

Font size

font-size Attribute sets the size of the text.

In web design, it is important to be able to manage text size. However, it should not be used to make paragraphs look like headings, or headings look like paragraphs by adjusting font size.

Always use the correct HTML tags, such as <h1> - <h6> for headings, and <p> only for paragraphs.

The font-size value can be an absolute or relative size.

Absolute size:

  • Set text to specified size
  • Does not allow users to change text size in all browsers (poor accessibility)
  • Absolute size is very useful when the physical size of the output is known

Relative size:

  • Set size relative to surrounding elements
  • Allow users to change text size in the browser

Note:If you do not specify a font size, the default size for normal text (such as paragraphs) is 16px (16px = 1em).

Font size set with pixels

Setting text size with pixels allows for complete control over text size:

Example

h1 {
  font-size: 40px;
}
h2 {
  font-size: 30px;
}
p {
  font-size: 14px;
}

Try It Yourself

Tip:If you use pixels, you can still use the zoom tool to adjust the size of the entire page.

Font size set with em

To allow users to adjust text size (in the browser menu), many developers use em instead of pixels.

W3C recommends using em size units.

1em is equal to the current font size. The default text size in browsers is 16px. Therefore, the default size 1em is 16px.

This formula can be used to calculate size from pixels to em: pixels/16=em.

Example

h1 {
  font-size: 2.5em; /* 40px/16=2.5em */
}
h2 {
  font-size: 1.875em; /* 30px/16=1.875em */
}
p {
  font-size: 0.875em; /* 14px/16=0.875em */
}

Try It Yourself

In the example above, the text size in em units is the same as the pixel size in the previous example. However, if em sizes are used, text size can be adjusted in all browsers.

Unfortunately, older versions of Internet Explorer still have issues. When zooming in on text, it becomes larger than it should be, and when zooming out, it becomes smaller.

A combination of percentages and Em is used

Example

body {
  font-size: 100%;
}
h1 {
  font-size: 2.5em;
}
h2 {
  font-size: 1.875em;
}
p {
  font-size: 0.875em;
}

Try It Yourself

Our code is currently running well! It displays the same text size in all browsers and allows all browsers to scale or adjust the text size!

Responsive Font Size

You can use vw Unit Set Text Size, which means "viewport width" ("viewport width").

As a result, the text size will follow the size of the browser window. Please adjust the size of the browser window to see how the font size scales:

Example

<h1 style="font-size:10vw">Hello World</h1>

Try It Yourself

The viewport (Viewport) is the size of the browser window. 1vw = 1% of the viewport width. If the viewport is 50 cm wide, then 1vw is 0.5 cm.