CSS Fonts

The font properties control the typeface, size and thickness of text.


font-family

Always write more than one font. If the first font is not on the visitor’s device, the browser tries the next one. The last one should be a generic family: serif, sans-serif, monospace, cursive or fantasy.

body { font-family: "Segoe UI", Arial, sans-serif; }
code { font-family: Consolas, monospace; }

Font names with spaces go inside quotes.

Output in the browser

Georgia (serif)

Arial (sans-serif)

Courier New (monospace)


Other font properties

PropertyExample
font-sizefont-size: 1.125rem;
font-weightnormal, bold or 100 to 900
font-stylenormal, italic, oblique
font-variantsmall-caps
h1 { font-size: 2rem; font-weight: 700; }
em { font-style: italic; }
.caps { font-variant: small-caps; }

Shorthand

p { font: italic bold 16px/1.5 Georgia, serif; }

The order is: style, weight, size/line-height, family. Size and family are required.


Web fonts

To use a font that visitors may not have, load it. The easy way is Google Fonts. Add a link in the head and use the name in CSS.

<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;700&display=swap">
body { font-family: "Roboto", sans-serif; }

Or host the font file yourself with @font-face.

@font-face {
  font-family: "MyFont";
  src: url("fonts/myfont.woff2") format("woff2");
  font-display: swap;
}
Note: Load only the weights you really use, because every font file makes the page heavier.

Summary

  • Write a list of fonts ending with a generic family.
  • Use rem for sizes and numbers 100 to 900 for weights.
  • Use Google Fonts or @font-face for custom fonts.
  • Next: CSS Links.

Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.