To embed a custom font into a CSS file, use the @font-face rule. Here’s a step-by-step guide:
1. Prepare Your Font Files
- Obtain the font files (e.g.,
.woff, .woff2, .ttf, .otf) and place them in your project directory (e.g., in a fonts folder).
2. Define the Font in CSS
Use @font-face in your CSS to declare the font and link to the files. Example:
@font-face {
font-family: 'CustomFont'; /* Name your font */
src:
url('fonts/CustomFont.woff2') format('woff2'),
url('fonts/CustomFont.woff') format('woff'),
url('fonts/CustomFont.ttf') format('truetype');
font-weight: normal; /* Specify weight (e.g., 400, 700) */
font-style: normal; /* Specify style (normal/italic) */
font-display: swap; /* Optional: Control loading behavior */
}
3. Use the Font in Your Styles
Apply the font to elements using the font-family name defined in @font-face:
body {
font-family: 'CustomFont', sans-serif; /* Fallback to sans-serif if needed */
}
Key Details:
- Font Formats:
- Use modern formats like
woff2 (best compression) and include fallbacks like woff or ttf for older browsers.
- Convert fonts to multiple formats using tools like Online Font Converter.
- Font Properties:
font-weight: Match the font’s actual weight (e.g., 700 for bold).
font-style: Use italic for italic variants.
- Font Loading:
font-display: swap ensures text remains visible while the font loads (prevents FOIT).
Example with Multiple Weights/Styles:
If your font has multiple weights (e.g., bold, italic), declare each variant separately:
/* Regular */
@font-face {
font-family: 'CustomFont';
src: url('fonts/CustomFont-Regular.woff2') format('woff2');
font-weight: 400;
font-style: normal;
}
/* Bold */
@font-face {
font-family: 'CustomFont';
src: url('fonts/CustomFont-Bold.woff2') format('woff2');
font-weight: 700;
font-style: normal;
}
/* Italic */
@font-face {
font-family: 'CustomFont';
src: url('fonts/CustomFont-Italic.woff2') format('woff2');
font-weight: 400;
font-style: italic;
}
Alternative: Use a Font Hosting Service
If you don’t want to host the font yourself, link to a CDN (e.g., Google Fonts):
@import url('https://fonts.googleapis.com/css2?family=Roboto:wght@400;700&display=swap');
Then use font-family: 'Roboto', sans-serif; in your CSS.
Licensing
Always ensure you have the legal right to use the font (check the license for .ttf/.otf files).