How to include a font in CSS
Adding a font to a page can be done with both HTML and CSS. Depending on your requirements you can use any of the approaches.
In this article, I will guide you through both approaches in detail of including a font.
Importing a font via HTML
Including a font with HTML is useful when you need to include a Google Font or any other 3rd party font that is hosted on a remote server.
To do that you can use the <link> element with the href attribute that is equal to the URL of the font in the <head> of your page.
Example:
Google Fonts will offer you a ready code snippet that you can insert into your HTML code.
Google Fonts link code snippet
That way you can add multiple fonts to your page. For each font, you can specify a <link> element with a unique URL. However, Google Fonts allows you to select multiple fonts and it will generate a single <link> element with all the fonts included as a URL query.
Google Fonts multiple link code snippet
To then apply an imported font to a text use the font-family property.
Example:
Google Fonts is a fast and easy way to include multiple fonts on your page. However, there are some points you should consider when using this approach, such as:
- The request to the remote server may fail, which will result in a font not being loaded;
- The request response time may take longer than from a self-hosted font, which affects page loading time;
- There can be privacy issues with loading Google Fonts (see GDPR).
Importing a font via CSS
You can also include a font with CSS. This approach is quite handy when you don’t have access to the HTML of the page as well as it is more flexible and allows for more customization.
Using the @import rule
The first way to include a font is to use the @import rule. Inside your CSS file or inside the <style> tag on your page define the @import rule with the specified URL of the font.
Example:
If you’re importing Google Fonts, then like in the example above they provide you with code snippet for the @import .
Google Fonts multiple import code snippet
Use the font-family property the same way when applying the font to the text.
Example:
Defining a font (font in a folder)
If you’re concerned about the page load time or the GDPR related issues, or if you have a custom font that’s not a Google Font, you can self-host a font.
In this case, you’ll need to have the font files stored in a separate folder of your project.
Font folder structure
And then you’ll need to define your custom font in the CSS file using the @font-face rule by specifying the font name and providing the path to your font files.
Как загрузить шрифт в html
Adding .ttf fonts using CSS: In the late 1980s, after getting beaten by adobe’s type 1 fonts, Apple came up with a new font format type which is .ttf(True Type Font). These fonts were so awesome that, they become the most common font formats all over the world in a very short time. In fact, windows itself started using them in there operating system.
Then, if you wish to use these font formats in your web pages, here is a detailed step by step explanation, how to import and use .ttf(true type fonts) in Html using CSS.
1. Download .ttf format file: The .ttf format is quite famous nowadays, these font files are available for free on Google. You can visit font space, font squirrel, etc websites that provide these fonts for free. Keep all the files in the same folder.
2. Create a HTML file: Create a HTML file and add a h2 tag for demonstrating our font style.
Web fonts
In the first article of the module, we explored the basic CSS features available for styling fonts and text. In this article we will go further, exploring web fonts in detail. We’ll see how to use custom fonts with your web page to allow for more varied, custom text styling.
| Prerequisites: | Basic computer literacy, HTML basics (study Introduction to HTML), CSS basics (study Introduction to CSS), CSS text and font fundamentals. |
|---|---|
| Objective: | To learn how to apply web fonts to a web page, using either a third party service, or by writing your own code. |
Font families recap
As we looked at in Fundamental text and font styling, the fonts applied to your HTML can be controlled using the font-family property. This takes one or more font family names. When displaying a webpage, a browser will travel down a list of font-family values until it finds a font available on the system it is running on:
This system works well, but traditionally web developers’ font choices were limited. There are only a handful of fonts that you can guarantee to be available across all common systems — the so-called Web-safe fonts. You can use the font stack to specify preferred fonts, followed by web-safe alternatives, followed by the default system font. However, this increases your workload because of the testing required to make sure that your designs work with each font.
Web fonts
But there is an alternative that works very well. CSS allows you to specify font files, available on the web, to be downloaded along with your website as it’s accessed. This means that any browser supporting this CSS feature can display the fonts you’ve specifically chosen. Amazing! The syntax required looks something like this:
First of all, you have a @font-face ruleset at the start of the CSS, which specifies the font file(s) to download:
Below this you use the font family name specified inside @font-face to apply your custom font to anything you like, as normal:
The syntax does get a bit more complex than this. We’ll go into more detail below.
Here are some important things to bear in mind about web fonts:
- Fonts generally aren’t free to use. You have to pay for them and/or follow other license conditions, such as crediting the font creator in your code (or on your site). You shouldn’t steal fonts and use them without giving proper credit.
- All major browsers support WOFF/WOFF2 (Web Open Font Format versions 1 and 2). Even older browsers such as IE9 (released in 2011) support the WOFF format.
- WOFF2 supports the entirety of the TrueType and OpenType specifications, including variable fonts, chromatic fonts, and font collections.
- The order in which you list font files is important. If you provide the browser with a list of multiple font files to download, the browser will choose the first font file it’s able to use. That’s why the format you list first should be the preferred format — that is, WOFF2 — with the older formats listed after that. Browsers that don’t understand one format will then fall back to the next format in the list.
- If you need to work with legacy browsers, you should provide EOT (Embedded Open Type), TTF (TrueType Font), and SVG web fonts for download. This article explains how to use the Fontsquirrel Webfont Generator to generate the required files.
You can use the Firefox Font Editor to investigate and manipulate the fonts in use on your page, whether they are web fonts or not. This video provides a nice walkthrough:
Active learning: A web font example
With this in mind, let’s build up a basic web font example from first principles. It’s difficult to demonstrate this using an embedded live example. So instead we would like you to follow the steps detailed in the below sections to get an idea of the process.
You should use the web-font-start.html and web-font-start.css files as a starting point to add your code to (see the live example). Make a copy of these files in a new directory on your computer now. In the web-font-start.css file, you’ll find some minimal CSS to deal with the basic layout and typesetting of the example.
Finding fonts
For this example, we’ll use two web fonts: one for the headings and one for the body text. To start with, we need to find the font files that contain the fonts. Fonts are created by font foundries and are stored in different file formats. There are generally three types of sites where you can obtain fonts:
- A free font distributor: This is a site that makes free fonts available for download (there may still be some license conditions, such as crediting the font creator). Examples include Font Squirrel, dafont, and Everything Fonts.
- A paid font distributor: This is a site that makes fonts available for a charge, such as fonts.com or myfonts.com. You can also buy fonts directly from font foundries, for example Linotype, Monotype, or Exljbris.
- An online font service: This is a site that stores and serves the fonts for you, making the whole process easier. See the Using an online font service section for more details.
Let’s find some fonts! Go to Font Squirrel and choose two fonts: a nice interesting font for the headings (maybe a nice display or slab serif font), and a slightly less flashy and more readable font for the paragraphs. When you’ve found a font, press the download button and save the file inside the same directory as the HTML and CSS files you saved earlier. It doesn’t matter whether they are TTF (True Type Fonts) or OTF (Open Type Fonts).
Unzip the two font packages (Web fonts are usually distributed in ZIP files containing the font file(s) and licensing information). You may find multiple font files in the package — some fonts are distributed as a family with different variants available, for example thin, medium, bold, italic, thin italic, etc. For this example, we just want you to concern yourself with a single font file for each choice.
Note: In Font Squirrel, under the «Find fonts» section in the right-hand column, you can click on the different tags and classifications to filter the displayed choices.
Generating the required code
Now you’ll need to generate the required code (and font formats). For each font, follow these steps:
- Make sure you have satisfied any licensing requirement if you are going to use this in a commercial and/or Web project.
- Go to the Fontsquirrel Webfont Generator.
- Upload your two font files using the Upload Fonts button.
- Check the checkbox labeled «Yes, the fonts I’m uploading are legally eligible for web embedding.»
- Click Download your kit.
After the generator has finished processing, you should get a ZIP file to download. Save it in the same directory as your HTML and CSS.
If you need to support legacy browsers, select the «Expert» mode in the Fontsquirrel Webfont Generator, select SVG, EOT, and TTF formats before downloading your kit.
Web services for font generation typically limit file sizes. In such a case, consider using tools such as:
-
for converting ttf to woff for converting from ttf to svg for converting from ttf to svg for converting from ttf to woff2
Implementing the code in your demo
At this point, unzip the webfont kit you just generated. Inside the unzipped directory you’ll see some useful items:
- Two versions of each font: the .woff , .woff2 files.
- A demo HTML file for each font — load these in your browser to see what the font will look like in different usage contexts.
- A stylesheet.css file, which contains the generated @font-face code you’ll need.
To implement these fonts in your demo, follow these steps:
- Rename the unzipped directory to something easy and simple, like fonts .
- Open up the stylesheet.css file and copy the two @font-face rulesets into your web-font-start.css file — you need to put them at the very top, before any of your CSS, as the fonts need to be imported before you can use them on your site.
- Each of the url() functions points to a font file that we want to import into our CSS. We need to make sure the paths to the files are correct, so add fonts/ to the start of each path (adjust as necessary).
- Now you can use these fonts in your font stacks, just like any web safe or default system font. For example:
You should end up with a demo page with some nice fonts implemented on them. Because different fonts are created at different sizes, you may have to adjust the size, spacing, etc., to sort out the look and feel.

Note: If you have any problems getting this to work, feel free to compare your version to our finished files — see web-font-finished.html and web-font-finished.css. You can also download the code from GitHub or run the finished example live.
Using an online font service
Online font services generally store and serve fonts for you so you don’t have to worry about writing the @font-face code. Instead, you generally just need to insert a simple line or two of code into your site to make everything work. Examples include Adobe Fonts and Cloud.typography. Most of these services are subscription-based, with the notable exception of Google Fonts, a useful free service, especially for rapid testing work and writing demos.
Most of these services are easy to use, so we won’t cover them in great detail. Let’s have a quick look at Google Fonts so you can get the idea. Again, use copies of web-font-start.html and web-font-start.css as your starting point.
- Go to Google Fonts.
- Search for your favorite fonts or use the filters at the top of the page to display the kinds of fonts you want to choose and select a couple of fonts that you like.
- To select a font family, click on the font preview and press the ⊕ button alongside the font.
- When you’ve chosen the font families, press the View your selected families button in the top right corner of the page.
- In the resulting screen, you first need to copy the line of HTML code shown and paste it into the head of your HTML file. Put it above the existing <link> element, so that the font is imported before you try to use it in your CSS.
- You then need to copy the CSS declarations listed into your CSS as appropriate, to apply the custom fonts to your HTML.
Note: You can find a completed version at google-font.html and google-font.css, if you need to check your work against ours (see it live).
@font-face in more detail
Let’s explore that @font-face syntax generated for you by Fontsquirrel. This is what one of the rulesets looks like:
Let’s go through it to see what it does:
- font-family : This line specifies the name you want to refer to the font as. This can be anything you like as long as you use it consistently throughout your CSS.
- src : These lines specify the paths to the font files to be imported into your CSS (the url part), and the format of each font file (the format part). The latter part in each case is optional, but is useful to declare because it allows browsers to more quickly determine which font they can use. Multiple declarations can be listed, separated by commas. Because the browser will search through them according to the rules of the cascade, it’s best to state your preferred formats, like WOFF2, at the beginning. / font-style : These lines specify what weight the font has and whether it is italic or not. If you are importing multiple weights of the same font, you can specify what their weight/style is and then use different values of font-weight / font-style to choose between them, rather than having to call all the different members of the font family different names. @font-face tip: define font-weight and font-style to keep your CSS simple by Roger Johansson shows what to do in more detail.
Note: You can also specify particular font-variant and font-stretch values for your web fonts. In newer browsers, you can also specify a unicode-range value, which is a specific range of characters you want to use out of the web font — in supporting browsers, only the specified characters will be downloaded, saving unnecessary downloading. Creating Custom Font Stacks with Unicode-Range by Drew McLellan provides some useful ideas on how to make use of this.
Variable fonts
There is a newer font technology available in browsers called variable fonts. These are fonts that allow many different variations of a typeface to be incorporated into a single file, rather than having a separate font file for every width, weight, or style. They are somewhat advanced for our beginner’s course, but if you fancy stretching yourself and looking into them, read our Variable fonts guide.
Summary
Now that you have worked through our articles on text styling fundamentals, it’s time to test your comprehension with our assessment for the module: Typesetting a community school homepage.
Подключаем веб-шрифты

Если на сайте используется шрифт, которого не окажется на устройстве пользователя (компьютер, ноутбук, планшет, смартфон), то шрифт будет заменён на стандартный. Следовательно дизайн не будет соответствовать действительности, а во многих случаях вёрстка ломается и выглядит некорректно
При подключении шрифта эта проблема решается, так как вместе с сайтом, загружаются используемые шрифты и сайт отображается корректно
Рассмотрим два способа подключить веб-шрифты
- Подключить веб-шрифт со стороннего сервиса, например Google Fonts через <link>
- Подключить файлы шрифтов через @font-face
Подключение веб-шрифтов с Google Fonts
Google Fonts содержит большое количество бесплатных шрифтов, которые часто используются в дизайне макетов
Заходим на официальный сайт Google Fonts и выбираем шрифт

Далее выбираем начертания веб-шрифта, например Regular (стандартной толщины) и Light (чуть более узкий, чем стандартный) — нажимаем на + Select this style. (Если нужно снять выбор — нажимаем на — Remove this style)

В правом верхнем углу нажимаем на иконку выбранных шрифтов

В открывшемся окне выбираем способ подключения <link> и копируем код расположенный ниже

Вставляем скопированный код в <head></head>
Чуть ниже копируем CSS свойство для использования подключеного шрифта

Используем подключенный шрифт в файле стилей CSS
Удобство данного способа в том, что добавив только одну строку в <head>, сразу можно использовать данный шрифт
Минусом этого способа является зависимость от сервиса Google Fonts. Если сервис перестанет работать, то подключенные шрифты не загрузятся
Данный способ полезен при создании быстрых прототипов верстки, для своих проектов/экспериментов
Подключение через @font-face
В дизайн макете сайта может быть использован нестандартный шрифт, который недоступен в Google Fonts. В таких случаях дизайнер вместе с дизайн макетом предоставляет файлы используемых шрифтов или скачиваете шрифт самостоятельно
Google Fonts также позволяет скачивать бесплатные шрифты, чтобы хранить на хостинге вместе с проектом и подключать их через @font-face
На странице выбранного шрифта, сверху справа нажимаем на кнопку Download family

Разархивируем скачанный zip-файл и видим файлы выбранного шрифта всех возможных его начертаний в формате *.ttf
У веб-шрифта должен быть определенный формат, который будет поддерживаться браузерами. На данный момент самый оптимальный формат веб-шрифтов — *.woff (Поддержка формата WOFF)
Чтобы конвертировать файлы формата *.ttf в формат *.woff воспользуемся бесплатным онлайн сервисом Transfonter
Переходим на официальный сайт сервиса Transfonter и нажимаем кнопку Add fonts

В открывшемся окне ищем папку в которую был разархивирован скачанный zip-файл, и выбираем необходимые начертания шрифта
Выбранные начертания шрифта будут загружены в сервис для конвертирования

Ниже расположены настройки конвертирования. Справа в списке форматов шрифтов выбираем только формат WOFF. Все остальные настройки оставляем по-умолчанию

Далее нажимаем кнопку Convert

После того, как шрифты будут сконвертированы, ниже слева появится ссылка Download для скачивания

Скачанный zip-файл содержит сгенерированные стили CSS для подключения шрифтов и *.woff файлы шрифтов

Файлы шрифтов копируем в папку fonts нашего проекта. Названия файлов шрифтов не изменяем.

Файл stylesheet.css содержит следующие сгенерированные стили
Копируем все содержимое файла stylesheet.css в самое начало нашего основного файла стилей CSS.
Так как основной файл стилей находится в папке css, отличной от папки, где лежат файлы шрифтов, необходимо внести некоторые изменения — в url добавляем относительный путь до папки fonts (остальные свойства не меняем)
Аналогично используем подключенный шрифт в файле стилей CSS
Преимущество данного способа в том, что веб-шрифты храняться на хостинге вместе с проектом, и не зависят от сторонних сервисов