How to Import Fonts With CSS
Importing via folder
We can import fonts using the @font-face
rule. The @font-face
rule lets us add custom fonts to use on a webpage. Once added to a stylesheet, the browser will download the font and then display it as specified in the CSS.
@font-face
should be added to the top of the stylesheet first before any other styles.
@font-face {
font-family: 'name';
src: url(path-to-file);
font-style: 'style'; // Optional
font-weight: 'weight'; // Optional
}
Properties:
font-family — Defines the name of the font. (Required)
src — Defines the URL where the font should be downloaded from. (Required)
font-style — Defines how the font should be styled. Default value is “normal”. (Optional)
font-weight — Defines the density of the font. Default value is “normal” (Optional)
Check out the MDN for more details on @font-face
Example:
Project Structure
project/
|
|-- fonts/
| |-- Open-Sans/
| |-- Open-Sans-Regular.ttf
|
`-- style.css
style.css
// Importing font@font-face {
font-family: 'Open Sans';
src: url('./fonts/Open-Sans/Open-Sans-Regular.ttf');
font-weight: 400;
font-style: normal;
}// Usageh1 {
font-family 'Open Sans', sans-serif;
font-weight: 400;
}
Importing via Webfonts (Google Fonts)
Another way of adding fonts to your project is by using Google Fonts. There are two ways to include a font in your web page. You can use the <link> tag, or you could use the @import rule.
Check out this article for more information on whether to use <link>
or @import
Folder Structure
project/
|
`-- index.html
`-- style.css
Standard Way
The standard way is adding the stylesheet to the <head> of your HTML document.
index.html
// Importing Font<head>
<link href="https://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet">
<link href="./style.css" rel="stylesheet">
</head>
style.css
// Usageh1 {
font-family 'Open Sans', sans-serif;
}
Using Import
Import involves importing the font in your css file.
style.css
// Importing Font@import url('https://fonts.googleapis.com/css?family=Open+Sans');// Usageh1 {
font-family 'Open Sans', sans-serif;
}
Stay hungry, stay foolish.