CSS Fonts
📣 Sponsor
Fonts are the first things we see when we open a web page, and the type of font used on a web page gives us an idea of the style of content. Picking the right fonts, therefore, is a critical part of the web design process.
Fonts are well supported in CSS, and this section of the guide we'll be looking at how to manipulate fonts on a page.
It is pretty common for web developers and designers to use Google Fonts as a repository for adding fonts to their websites. If you do not add fonts to your website using font files like those provided by Google Fonts, then the only fonts available to the user will be the ones installed on their local computer.
Font Family
Probably the most useful font property to know, font-family
lets you set the font for a specific element. It accepts a comma separated list of fonts. It is best practice to follow a list of fonts with a keyword, like sans-serif
. That means if none of the fonts listed are installed, the system default sans-serif
will be used.
div {
font-family: 'Helvetica Neue', Arial, Helvetica, sans-serif;
}
Note also that single word fonts do not require speech marks, but multi word fonts do. The keywords which can be used for font-family are:
- serif - a font which has serifs, i.e. Times New Roman
- sans-seri - a font which has no serifs, i.e. the font used on this page
- monospace - a font with even spacing, for coding usually, i.e. Menlo
- fantasy - a decorative font, i.e. Impact
- cursive - a font which mimics handwriting, i.e. Apple Chancery
Font Size
A font size is set with font-size
. This accepts any CSS unit, but the most common are pixels (px
) or rem
/em
, which refers to the distance from the very top to the very bottom of the current font.
Usually, it is better practice to use em
or rem
.
div {
font-size: 1.5rem;
}
Font Style
In CSS, font-style
refers to if a font is oblique
or italic
, both different styles of slanted fonts. It can be set to either of these values, or normal
.
div {
font-style: italic;
}
I am italic!
Line Height
The height of a line of text can also be configured with CSS. To do this, we use line-height
. As expected, this accepts any CSS unit, but the most common are:
- no units - refers to the current font size, so 1 would be 16px for a 16px font, 2 would be 32px.
- em/rem - as previously mentioned, refers to the font size.
- px - the line height as defined in specific pixel units.
div {
line-height: 1.5rem;
}
li {
line-height: 1.25;
}
More Tips and Tricks for CSS
- CSS Individual Transform Properties
- Using Only CSS to Recreate Windows 98
- How to Make your text look crisp in CSS
- A first look at CSS When and Else Statements
- Parent Selection in CSS: how the CSS has selector works
- How to Animate SVG paths with CSS
- The Quick Guide to Dark Mode
- CSS Units
- The Interactive Guide to CSS Grid
- Making 3D CSS Flippable Cards