Using custom fonts
Custom fonts are a fun way to spice up your website.
In order to use them, you need one of two things:
- The actual font file itself, uploaded onto your website or,
- A link to the font file that someone else is hosting
There are tons of free fonts available on websites like DaFont or Font Squirrel that you can upload to your site.
There's also Google Fonts which can be somewhat bulky, but useful if you'd like instant and free webfonts. The method for adding those is slightly different and not covered here.
Keep in mind that while most font files aren't huge, they do take up more space on your webserver than your average HTML file.
To add custom fonts to your website:
- Grab the font files you want to use. If it's in a .zip or .rar file, you'll want to extract it. The most common font file types are .ttf (truetype) and .otf (opentype) so that's what you're looking for. Upload this to your website, and copy the link to its location.
- Then, in your stylesheet, add the following:
- Change the font-family: property to something that corresponds to that font. This name is going to be how you refer to the font when assigning it to elements.
- Change the src: to the location of the font file.
@font-face {
font-family: "My font name";
src: url("/fonts/myfont.ttf") format("truetype");
/* or: */
src: url("/fonts/myfont.otf") format("opentype"); */
}
Custom font styles
Some fonts provide individual files for each style (such as bold, italic, bold italic, etc.) In this case, if you want to use the associated font with its weight, you’ll need an @font-face rule for each style with special instructions.
Here is an example which has separate files for the regular, bold, and bold-italic font styles:
@font-face {
font-family: Nunito;
src: url('https://sadhost.neocities.org/fonts/Nunito-Regular.ttf') format("truetype");
}
@font-face {
font-family: Nunito;
src: url('https://sadhost.neocities.org/fonts/Nunito-Bold.ttf') format("truetype");
font-weight: bold; /* bold */
}
@font-face {
font-family: Nunito;
src: url('https://sadhost.neocities.org/fonts/Nunito-Italic.ttf') format("truetype");
font-style: italic; /* italic */
}
@font-face {
font-family: Nunito;
src: url('https://sadhost.neocities.org/fonts/Nunito-BoldItalic.ttf') format("truetype");
font-style: italic; /* italic */
font-weight: bold; /* bold */
}
Notice how in the above example, all of the font-family properties have the same name. This is because we’re using all of the various styles (regular, italic, bold, bold italic) for the same font. Notice that the src: value changes to the appropriate font file.
To use this font, you only need to specify: font-family: Nunito and depending on the other styles (whether the font is italic, bold, etc.) it will show up correctly.