@font-face
is one of several CSS at-rules, like
@media
,
@import
,
@keyframes
. At-rules are ways of encapsulating several rules together in a declaration to serve as instructions to the browser’s CSS processor.
To include fonts using
@font-face
, you have to:
1. load the font file onto your servers in a variety of formats to support all the different browsers
2. name, describe, and link to that font in an @font-face rule
3. include the font’s name in a font-family property value, just as you would for system fonts
@font-face syntax
@font-face {
font-family: '<fontName>';
src: <source>;
font-weight: <weight>;
font-style: <style>;
}
The font family and source are required, but the weight and style are optional.
For every font you have to include a separate at-rule for each variation of the font—regular, thin, thick, italic, black, and so on.
The
font-family
part of the
@font-face
at-rule declaration is slightly different from the font-family property with which you’re already familiar. In this case, we’re declaring a name for our font, rather than assigning a font with a given name to an element.
snippet
@font-face {
font-family: 'LeagueGothic';
}
@font-face {
font-family: 'AcknowledgementMedium';
}
Declaring Font Sources
The src property can take several formats. Additionally, you can declare more than one source.
snippet
@font-face {
font-family: 'LeagueGothicRegular';
src: url('../fonts/League_Gothic-webfont.eot') format('eot'),
url('../fonts/League_Gothic-webfont.woff') format('woff'),
url('../fonts/League_Gothic-webfont.ttf') format('truetype'),
url('../fonts/League_Gothic-webfont.svg#webfontFHzvtkso') format('svg');
}
Example:-
snippet
@font-face {
font-family: MuseoSans;
src:
url("assets/type/museosans.eot") format("embedded-opentype"),
url("assets/type/museosans.woff") format("woff"),
url("assets/type/museosans.ttf") format("truetype");
}
Tip: It is always wise to use the real font name. It will help you to keep your style sheet understandable.
The first src defines the URL of the .eot file, which is necessary for compatibility with Internet Explorer (versions 5 through 9).
url("assets/type/museosans.woff") format("woff"),
url("assets/type/museosans.ttf") format("truetype");
The successive src attributes are needed to guarantee compatibility with all modern desktop and mobile browsers. The .WOFF format is used by Firefox, while the .TTF format is used by the browsers based on WebKit.
Making the font work
Rename the font defined with the attribute font-family inside your style sheet—for example, on the tag
.
snippet
body {
font: 14px MuseoSans, "Helvetica Neue", Arial, sans-serif;
}