@font-face
Written By: Avinash Malhotra
Updated on

CSS3 Fonts
CSS3 includes @font-face rule to embedded fonts in css. But till CSS2, only Web Safe fonts were used. Embedded fonts supports five extensions, woff, woff2, otf/ttf, eot and svg. In the next example, see how to add font in html page using @font-face rule.
How to add font in html page
<style>
@font-face{
font-family:'helvetica-neue';
src:url('../fonts/helvetica-neue.woff') format('woff');
}
body{
font-family:'helvetica-neue', sans-serif;
}
</style>
Create a folder namedfonts
in root directory, and add helvetica-neue font
with woff extension.
Web Fonts Extensions
Web supports five fonts extensions, woff, woff2, ttf/otf, eot and svg. Here is a comparison of web fonts.
Extension | Full Form | Browser Support |
---|---|---|
woff | Web Open Font Format | All browsers except IE8 |
woff2 | Web Open Font Format Version 2 (30% lighter than woff) | Only Chrome 40+, Chrome (Android) 46+, Firefox 40+, Opera 32+, |
otf / ttf | Other Type Fonts and True Type Font | All browsers except IE8 |
EOT | Embedded OpenType | Only IE 8 to 11 |
SVG | Scalable Vector Graphics | Only for Safari (MacOS) 8+, Safari (IOS) 8.4+ |
Multiple Fonts extension in font face
Some time a particular OS doesn't understand a font extension and discard that font. To avoid this, use Multiple Fonts extension in font face rule.
Always prefer lighter fonts first to improve pagespeed. In example below, woff2 is lighter than woff, which is lighter than ttf.
<style>
@font-face{
font-family:'helvetica-neue';
src:url('../fonts/helvetica-neue.woff2') format('woff2'),
url('../fonts/helvetica-neue.woff') format('woff'),
url('../fonts/helvetica-neue.ttf') format('ttf'),
url('../fonts/helvetica-neue.otf') format('otf'),
url('../fonts/helvetica-neue.svg') format('svg');
}
body{
font-family:'helvetica-neue', sans-serif;
}
</style>
@font-face rule works on IE 9 and above browsers only. Use font replacement for embedded font.