Ensuring Consistent Fonts Across Browsers: Using Multiple Font Files
Here's how it works using Cascading Style Sheets (CSS):
-
Specifying Font Files: Within the
@font-face
rule, you use thesrc
property to define a list of URLs pointing to your font files. Each font file can have a different format.-
Common Font Formats:
- WOFF2 (.woff2): A compressed version of the WOFF format, offering the best performance and compatibility.
- WOFF (.woff): An older format with good compatibility across most browsers.
- TTF (.ttf): A widely supported format, but larger in file size.
-
Here's an example of how you might use @font-face
to include multiple font files for a font family called 'MyFont':
@font-face {
font-family: 'MyFont';
src: url('font.woff2') format('woff2'),
url('font.woff') format('woff'),
url('font.ttf') format('truetype');
}
body {
font-family: 'MyFont', sans-serif;
}
In this example, the browser will first try to use 'font.woff2' because it's the most performant option. If the browser doesn't support WOFF2, it will then try 'font.woff' and then 'font.ttf' as backups.
Example 1: Including Multiple Weights
This example defines a font family named 'Roboto' with two weight variations: regular and bold.
@font-face {
font-family: 'Roboto';
src: url('Roboto-Regular.woff2') format('woff2'),
url('Roboto-Regular.woff') format('woff'),
url('Roboto-Regular.ttf') format('truetype');
font-weight: 400; /* Regular weight */
}
@font-face {
font-family: 'Roboto';
src: url('Roboto-Bold.woff2') format('woff2'),
url('Roboto-Bold.woff') format('woff'),
url('Roboto-Bold.ttf') format('truetype');
font-weight: 700; /* Bold weight */
}
h1 {
font-family: 'Roboto', sans-serif;
font-weight: 400; /* Use regular weight by default */
}
.bold-text {
font-weight: 700; /* Apply bold weight for specific elements */
}
Example 2: Including Italic Style
This example defines a font family named 'OpenSans' with both regular and italic styles.
@font-face {
font-family: 'OpenSans';
src: url('OpenSans-Regular.woff2') format('woff2'),
url('OpenSans-Regular.woff') format('woff'),
url('OpenSans-Regular.ttf') format('truetype');
font-style: normal; /* Regular style */
}
@font-face {
font-family: 'OpenSans';
src: url('OpenSans-Italic.woff2') format('woff2'),
url('OpenSans-Italic.woff') format('woff'),
url('OpenSans-Italic.ttf') format('truetype');
font-style: italic; /* Italic style */
}
body {
font-family: 'OpenSans', sans-serif;
font-style: normal; /* Use regular style by default */
}
.italic-text {
font-style: italic; /* Apply italic style for specific elements */
}
-
Using Web Font Services:
-
Here's an example of using Google Fonts to include the 'Open Sans' font family with various weights and styles:
@import url("https://fonts.googleapis.com/css2?family=Open+Sans:wght@300;400;600;700&display=swap");
This code snippet imports the 'Open Sans' font with weights 300, 400 (regular), 600, and 700 (bold) from Google Fonts.
-
Font Subsetting:
fonts css font-face