How to add font to css

How to add font to css

CSS Web Fonts

The CSS @font-face Rule

Web fonts allow Web designers to use fonts that are not installed on the user’s computer.

When you have found/bought the font you wish to use, just include the font file on your web server, and it will be automatically downloaded to the user when needed.

Your «own» fonts are defined within the CSS @font-face rule.

Different Font Formats

TrueType Fonts (TTF)

TrueType is a font standard developed in the late 1980s, by Apple and Microsoft. TrueType is the most common font format for both the Mac OS and Microsoft Windows operating systems.

OpenType Fonts (OTF)

OpenType is a format for scalable computer fonts. It was built on TrueType, and is a registered trademark of Microsoft. OpenType fonts are used commonly today on the major computer platforms.

The Web Open Font Format (WOFF)

WOFF is a font format for use in web pages. It was developed in 2009, and is now a W3C Recommendation. WOFF is essentially OpenType or TrueType with compression and additional metadata. The goal is to support font distribution from a server to a client over a network with bandwidth constraints.

The Web Open Font Format (WOFF 2.0)

TrueType/OpenType font that provides better compression than WOFF 1.0.

SVG Fonts/Shapes

SVG fonts allow SVG to be used as glyphs when displaying text. The SVG 1.1 specification define a font module that allows the creation of fonts within an SVG document. You can also apply CSS to SVG documents, and the @font-face rule can be applied to text in SVG documents.

Embedded OpenType Fonts (EOT)

EOT fonts are a compact form of OpenType fonts designed by Microsoft for use as embedded fonts on web pages.

Browser Support for Font Formats

The numbers in the table specifies the first browser version that fully supports the font format.

Font format
TTF/OTF9.0*4.03.53.110.0
WOFF9.05.03.65.111.1
WOFF214.036.039.010.026.0
SVGNot supportedNot supportedNot supported3.2Not supported
EOT6.0Not supportedNot supportedNot supportedNot supported

*IE: The font format only works when set to be «installable».

Using The Font You Want

In the @font-face rule; first define a name for the font (e.g. myFirstFont) and then point to the font file.

Tip: Always use lowercase letters for the font URL. Uppercase letters can give unexpected results in IE.

To use the font for an HTML element, refer to the name of the font (myFirstFont) through the font-family property:

Example

@font-face <
font-family: myFirstFont;
src: url(sansation_light.woff);
>

div <
font-family: myFirstFont;
>

Using Bold Text

You must add another @font-face rule containing descriptors for bold text:

Example

The file «sansation_bold.woff» is another font file, that contains the bold characters for the Sansation font.

Browsers will use this whenever a piece of text with the font-family «myFirstFont» should render as bold.

This way you can have many @font-face rules for the same font.

CSS Font Descriptors

The following table lists all the font descriptors that can be defined inside the @font-face rule:

Подключение шрифтов в CSS

Если не вникать в подробности, по быстрому подключить шрифт можно так:

Такой метод вполне работает в большинстве браузеров, но неверен. В данном примере упущено:

Локальные шрифты

Правило @font-face src позволяет задать название локального шрифта, т.е. если у пользователя на компьютере уже установлен нужный шрифт, то будет использоваться именно он, при этом существенно увеличится скорость загрузки и отрисовки страницы.

Можно указать несколько названий:

Форматы шрифтов

Сегодня используются четыре формата, рассмотрим их подробнее:

TTF/OTF – работают в большинстве браузеров, кроме IE.

How to add font to css. Смотреть фото How to add font to css. Смотреть картинку How to add font to css. Картинка про How to add font to css. Фото How to add font to css

EOT – создан Microsoft, представляет сжатую копию шрифта TTF, поддерживается только в IE.

How to add font to css. Смотреть фото How to add font to css. Смотреть картинку How to add font to css. Картинка про How to add font to css. Фото How to add font to css

WOFF – формат представляет собой сжатый шрифт в формате TTF/OTF.

How to add font to css. Смотреть фото How to add font to css. Смотреть картинку How to add font to css. Картинка про How to add font to css. Фото How to add font to css

WOFF2 – имеет улучшенное сжатие, по сравнению с первой версией.

How to add font to css. Смотреть фото How to add font to css. Смотреть картинку How to add font to css. Картинка про How to add font to css. Фото How to add font to css

Как видно нет единого формата, который поддерживается всеми браузерами, поэтому нужно делать подключение нескольких файлов, браузер сам выберет подходящий формат. Рекомендуется подключать файлы шрифтов по приоритету:

Если в наборе есть не все форматы, их можно получить перекодировкой с помощью сервисов onlinefontconverter.com или convertio.co.

Разные начертания шрифтов

Пример подключения шрифта «Crimson Text» в разных начертаниях:

The Easy Way to Add Fonts to Your Website (Including Custom Fonts)

Philip Westfall, August 12, 2021

Adding a unique font to your website is a great way to make your design stand out online.

In this article, I will walk you through the step-by-step process for adding any font to your website.

Note: because websites are not all built and managed the same way, I will introduce the most universal approach for adding custom fonts and then explain how the most popular website building platforms support custom fonts.

Contents:

What fonts can be used on the Web?

Technically speaking, you can add just about any font to any website.

However, when searching for a font online, you always want to keep in mind the price, theВ license agreement, and the installation method.

Without further ado, here are some of the most popular font libraries to help you find that perfect font:

Google Fonts (FREE)

Google fonts boast an impressive library of close to 1000 libre license fonts that can be browsed via their interactive web directory. Because of theirВ Developer API, Google Fonts are arguably the easiest fonts to add to your site and where I would recommending starting your search.

How to add font to css. Смотреть фото How to add font to css. Смотреть картинку How to add font to css. Картинка про How to add font to css. Фото How to add font to css

Adobe Fonts (Premium)

Adobe Fonts, (previously Typekit) provides a collection of +14,000 stunning fonts. The new and improved service now provides Creative Cloud subscribersВ subscribers with easy access to their entire library of fonts through the click of a button. Unlike Typekit, Adobe Fonts has removed limits on page views and has made all their fonts accessible for both desktop and web use.

How to add font to css. Смотреть фото How to add font to css. Смотреть картинку How to add font to css. Картинка про How to add font to css. Фото How to add font to css

Custom Fonts (Font Squirrel)

On top of offering aВ selection of free fontsВ licensed for commercial work, Font Squirrel is well known for theirВ Font IdentifierВ andВ Font Generator.

How to add font to css. Смотреть фото How to add font to css. Смотреть картинку How to add font to css. Картинка про How to add font to css. Фото How to add font to css

Different Font Formats and Browser Support

Over the past few years, modern browsers have dramatically improved how they support custom fonts. However, even today, not all formats are supported on every browser.

Here are the most popular browsers and what font format they currently support:

How to add font to css. Смотреть фото How to add font to css. Смотреть картинку How to add font to css. Картинка про How to add font to css. Фото How to add font to css

I’d always recommend using TTF/OTF and WOFF to ensure that your fonts are supported across all browsers.

How to add custom fonts to your website using @font-faceВ

The @font-face CSS rule explained below is the most common approach for adding custom fonts to a website.

Step 1: Download the font

Find the custom font you want to use on your website, and then download the TrueType Font file format (.ttf). You can also download the OpenType Font format (.otf)

Step 2: Create a WebFont Kit for cross-browsing

Step 3: Upload the font files to your website

Using your FTP or file manager, upload all the font files found within your Web Font Kit to your website.* Typically this kit will include multiple file extensions such as (.eot), (.woff), (.woff2), (.ttf) and (.svg).

Your kit will also include a Cascading Style Sheet (.css) that you will need to update and upload in step 4.

*This step will vary greatly based upon how your website is built and hosted.

Step 4: Update and upload your CSS file

Open the CSS file in a text editor such as Textedit, NotePad orВ Sublime.

Replace the existing source URL with the new URL you created by uploading each file.

By default, the source URL location is set within the downloaded Web Font Kit. It needs to be replaced by the location on your server.

Here’s a quick example:

Before update:

@font-face <
font-family: «CustomFont»;
src: url(«CustomFont.eot»);
src: url(«CustomFont.woff») format(«woff»),
url(«CustomFont.otf») format(«opentype»),
url(«CustomFont.svg#filename») format(«svg»);
>

After update:

@font-face <
font-family: «CustomFont»;
src: url(«https://yoursite.com/css/fonts/CustomFont.eot»);
src: url(«https://yoursite.com/css/fonts/CustomFont.woff») format(«woff»),
url(«https://yoursite.com/css/fonts/CustomFont.otf») format(«opentype»),
url(«https://yoursite.com/css/fonts/CustomFont.svg#filename») format(«svg»);
>

Once you’ve updated the CSS file, you need to upload it to your website (server).

Step 5: Use the custom font in your CSS declarations

Now that your Cascading Style Sheet and font files are uploaded to your server, you can start using your custom font in your CSS declarations to help improve the look of the HTML.

This can be done in multiple ways, including adding site-wide declarations to your main CSS file.

Here is a quick example:

h1 <
font-family: ‘CustomFont’, Arial, sans-serif;
font-weight:normal;
font-style:normal;
>

How to add fonts in popular website building tools

Content Management Systems (WordPress, Drupal, Joomla, etc.)

There are a few different ways you can add custom fonts to a Content Management System (CMS) likeВ WordPress (WP):

Adding custom fonts using @font-face CSSAdd fonts using aВ WordPress pluginВ Manually adding fonts fromВ Google Fonts

Generally speaking, the 5 step process shown above will be the default approach when adding a custom font to a CMS. Although the process might seem pretty straightforward for people experienced with manipulating code, novice users will often look for an alternative.

If you are using WP and don’t have any experience editing the source code (theme files), you will most likely want to rely on a typography plugin. Plugins make it easier to add custom fonts without having to write any code yourself.

The only thing I caution about when using WP plugins is that they can cause a variety of issues on your website. It’s important to always research plugins before using them on your site.

Finally, because Google Fonts offers a developer API, you can also choose to “manually add” those fonts to your theme using the functions.php file.

Website Builders (PageCloud, Squarespace, Wix, Weebly)

There are a ton of website builder options online that manage custom fonts in different ways.В

Google Fonts

For the most part, the top website builders make it pretty easy to add fonts from popular sites like Google Fonts.

For example, with PageCloud, adding a font from Google couldn’t be easier. All you need to do is copy and paste the font, and voila, your font is added to your page and ready to be styled in any way!

How to add font to css. Смотреть фото How to add font to css. Смотреть картинку How to add font to css. Картинка про How to add font to css. Фото How to add font to css

However, not all website builders make it this easy to add a Google Font.

For example, adding a Google Font in Weebly will require you to edit the source code (CSS) of your website. They explain theВ 8 step processВ in their knowledge base.

How to add font to css. Смотреть фото How to add font to css. Смотреть картинку How to add font to css. Картинка про How to add font to css. Фото How to add font to css

Here is a short list of the top website builders and how they manage Google Fonts:

As you can see, each website builder uses a different approach for adding fonts that can range from very easy to somewhat complicated.

How to add font to css. Смотреть фото How to add font to css. Смотреть картинку How to add font to css. Картинка про How to add font to css. Фото How to add font to css

Custom Fonts

In most cases, when looking to add a custom font that does not exist within Google Fonts, you will need to edit the CSS on your website. This process can be dramatically different based on the website builder you decide to use.

I’d recommend searching through their respective knowledge bases and community forums for more information.

For example, theВ process of adding a custom font with PagecloudВ is very similar to the step-by-step guide provided above.

Summary

Regardless of your experience with CSS, following the instructions in this article will give you the ability to add any font to any website building platform.

However, once you’ve successfully added the font you wanted to your website, the questions you need to ask are:

Do you have the ability to customize the look of the font?В (font weight, color, line-height, letter spacing, opacity, etc)Can you customize the layout of your site to make the font stand-out(position of text, images, videos, etc)

If you don’t have extensive experience with CSS, these customizations can be very challenging when using a CMS or a rigid template based website builder like SquareSpace.

This is why I’d recommend using a flexible website builder likeВ PagecloudВ that gives you unrivalled flexibility when looking to create a unique layout with virtually unlimited style and font options. Sign up today to try Pagecloud’s website builder and e-commerce platform!В

Philip Westfall

Share

Create your no-code landing page, website, or online store in no time.

Publish your homepage for free, no credit card required.

Enjoyed the read?

Join our monthly newsletter for helpful tips on SEO, Web design, and more!

Как подключить и оптимизировать нестандартные шрифты

How to add font to css. Смотреть фото How to add font to css. Смотреть картинку How to add font to css. Картинка про How to add font to css. Фото How to add font to css

Текст — основная часть контента на большинстве сайтов, и важно грамотно подходить к его отрисовке. В этой статье мы разберём базовые моменты, касающиеся подключения и оптимизации шрифтов.

Самый простой вариант — вообще не подключать сторонние шрифты и пользоваться стандартными. Это хорошо знакомые Arial, Times New Roman и так далее — эти шрифты называются веб-безопасными, достаточно просто указать название одного из таких шрифтов в коде и всё будет работать.

Но чаще дизайн макета не позволяет обойтись веб-безопасным шрифтом, а требует использовать какой-то нестандартный. Тогда файл со шрифтом нужно подгружать с сервера по той же схеме, что и остальные ресурсы — CSS-файлы, изображения и так далее. Он может весить довольно много, поэтому для быстрой загрузки страницы выгоднее сначала рассмотреть использование стандартных шрифтов. Но даже с нестандартными шрифтами можно избежать большинства проблем, если уделить внимание оптимизации.

Для начала стоит выбрать правильный формат шрифта. TTF и OTF — форматы, которые предоставляются с минимальным сжатием или совсем без него. Их стоит использовать только в том случае, если нужна поддержка очень старых браузеров. Во всех остальных ситуациях можно выбрать WOFF и WOFF2 — форматы, которые отличаются высокой степенью сжатия. WOFF2 — усовершенствованная версия предшественника, этот формат можно считать лучшим из существующих. Тем не менее, поддержка WOFF2 хотя и очень хорошая, но пока не абсолютная, поэтому в качестве подстраховки для не самых современных браузеров стоит использовать WOFF.

Подключение шрифтов с помощью Google Fonts

Есть простой и удобный способ подключить нестандартный шрифт — использовать Google Fonts. Это бесплатный сервис, с помощью которого можно подключать шрифты, но не хранить их на своём сервере. Чтобы им воспользоваться, необходимо выбрать шрифт и добавить одно или несколько нужных начертаний, а затем вставить в ссылку, которую сгенерирует Google Fonts во вкладке Embed.

How to add font to css. Смотреть фото How to add font to css. Смотреть картинку How to add font to css. Картинка про How to add font to css. Фото How to add font to css

Этого достаточно, чтобы шрифт подключился. Теперь его можно использовать в свойстве font-family без каких-либо дополнительных действий.

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

Плюсы этого способа — простота использования и всегда актуальные версии шрифтов, Google Fonts их часто обновляет. Но у него есть и минус — запросы к сторонним серверам могут негативно повлиять на скорость загрузки страницы. Если выбираете этот способ, стоит обратить внимание на оптимизацию.

Подключение шрифтов с помощью @font-face

Название шрифта, которое затем нужно использовать, чтобы задать элементам подключённый шрифт.

Адрес файла со шрифтом, который нужно подключить, и его формат. Если адресов несколько, их можно указать через запятую. В этом случае важен порядок — браузер будет последовательно пытаться подключить файлы. Первым должен быть самый подходящий формат, а далее — запасные варианты.

Также с помощью функции local можно добавить возможность перед загрузкой шрифта с сервера проверить, установлен ли он на компьютере пользователя. Если да, запроса к серверу за шрифтом не будет — при рендеринге используется локальная версия. Но у этого способа есть минус — шрифт на компьютере пользователя может быть устаревшим, и тогда страница отобразится не совсем так, как было задумано.

Базовый вариант правила:

Для улучшения производительности правило @font-face лучше всего прописывать в самом начале CSS-файла. Так браузер сможет раньше начать обработку шрифта.

Оптимизация

Выбор современного формата шрифта, который обладает хорошей степенью сжатия — это только первый шаг к оптимизации. Можно сделать гораздо больше, чтобы увеличить скорость загрузки страницы и сделать пользовательский опыт при взаимодействии с интерфейсом приятнее.

FOIT, FOUT и FOFT

Пока шрифт загружается, при рендеринге можно наблюдать разное поведение текста.

FOIT (Flash of Invisible Text) — с англ. «мелькание невидимого текста». При таком поведении, пока шрифт не загрузится, текст не отображается и появляется только после загрузки шрифта. Значительная проблема — во время загрузки нет доступа к текстовому контенту.

FOUT (Flash of Unstyled Text) — с англ. «мелькание неоформленного текста». Во время загрузки используется шрифт, заданный по умолчанию (системный, например), а после загрузки страница перерисовывается с использованием загрузившегося шрифта. Эта перерисовка довольно заметна и может быть нежелательна.

FOFT (Flash of Faux Text) — с англ. «мелькание синтезированного текста». Это поведение можно наблюдать в промежутке, когда основное начертание уже загрузилось, а дополнительные (жирное, курсивное и так далее) — нет. Браузер имитирует нужное начертание до загрузки настоящей версии. В этом случае страница может перерисовываться несколько раз по мере загрузки начертаний.

Свойство font-display

У свойства есть несколько значений, которые определяют поведение текста во время загрузки шрифта:

Предзагрузка шрифтов

Ещё один способ оптимизации — предварительная загрузка шрифтов. С её помощью можно изменить обычную приоритизацию загрузки ресурсов, тем самым сказав браузеру, что важно загрузить шрифт в первую очередь.

Стоит учесть, что браузер загрузит шрифт в любом случае — даже если он не используется на странице. И, обладая высоким приоритетом, эта загрузка может блокировать загрузку других ресурсов, поэтому нужно грамотно выбирать, что именно предзагружать. Например, если на странице используются три разных шрифта, стоит предзагрузить только основной шрифт без дополнительных начертаний.

Для того, чтобы предзагрузка сработала, нужно поместить в ссылку на шрифт и задать атрибуту rel значение preload :

Уменьшение количества глифов шрифта

По умолчанию шрифт может содержать глифы (буквы, символы) разных языков и просто редко используемые. С помощью свойства unicode-range можно установить диапазон нужных символов в системе Unicode, тогда браузер будет подгружать сабсет (подмножество) шрифта только в тот момент, когда на странице появится символ из этого диапазона. Предварительно нужно подготовить файлы шрифтов, разбив их на группы.

Например, можно отдельно подключить латиницу и кириллицу, если на сайте представлены версии на двух языках. И с помощью unicode-range браузер поймёт, какой сабсет нужен для конкретной страницы, и загрузит только его. Такой файл будет иметь меньший вес и ускорит загрузку страницы.

Также можно проанализировать, какие конкретно глифы используются на сайте и создать кастомный сабсет исключительно с ними. Для этого есть специальные инструменты.

Google Fonts по умолчанию использует сабсеты. Это можно увидеть, открыв CSS-файл, который подключается в при использовании сервиса. Для каждого языка есть отдельный сабсет. Пример для латиницы и кириллицы:

В статье разобраны только базовые способы оптимизации шрифтов. Но даже их достаточно, чтобы улучшить пользовательский опыт и значительно уменьшить вес файлов шрифтов, ускорив тем самым загрузку страницы.

Полезности

Подключение шрифтов — часть вёрстки

А научиться вёрстке проще, чем кажется. Скидка 1000₽ по промокоду SKUCHNO.

How to Setup Custom Fonts with CSS & @font-face

November 19, 2019

Ready? Let’s dive in:

Here’s a video, if you prefer to watch instead of read:

Step 1: Get all the font files you need for cross-browser support

To meet the best cross-browser standards, you’ll need 5 specific font file extensions of your custom font added to your project.

In fact, here are the 5 file extensions you’ll need:

If you have all of these font file extensions already, then you can skip straight ahead to step 2.

But what if you don’t have all the font-file extensions?

Thankfully, solving this problem is quick and easy.

Just head over to a free font generator (I like to use Transfonter), and upload your font files there.

For example, on the Transfonter website, press the Add fonts button:

Select the font files to upload (note here that I’ve uploaded the regular, italic, bold and bold italic as I want to use these in my project):

Make sure you have all the font formats selected, and leave the “Family support” option to on:

Finally, press the Convert button and download:

Here’s how mine looks, various font weights and styles with different file extensions:

Awesome! Now you’ve got all the font files, we can start to add the custom font to our project.

Step 2: Add the font files to your project

You might be thinking: where do I put all the font files?

Is there a specific folder I should be using?

It depends on the structure of your project. It’s pretty difficult to go wrong though.

As you will likely have quite a few font files, my recommendation would be to place all of the font files in a folder called “Fonts”, like this:

Groovy! With all the font files added to your project, it’s time to use @font-face …

Step 3: Use @font-face in CSS to leverage the font files

Your font files are now in your project. It’s time to write some CSS so the font is available for you to style the typography!

Open your CSS file (or preprocessor file) and drop in a @font-face declaration, like this:

You’ll need to swap out the font-family CaviarDreams with the name of your custom font.

You’ll also need to change the value referenced inside each url() so that it references the location of the font (where you placed the font files in your project. See step 2 above)

The example above only covers 1 font family, 1 font weight, and 1 font style.

What about multiple font weights like semi-bold or light? Or the italic version of each font weight?

For that, you’ll simply need to add more @font-face declarations:

As you can see, this code can get pretty long pretty quickly.

For those leveraging a CSS preprocessor like Sass, creating your own mixin to solve for this could be an option.

Note in the above CSS example that the font-weight and the font-style are adjusted for each @font-face declaration to match the font file being referenced.

For example, the CaviarDreams-BoldItalic font file has a font-weight of 700 and font-style is italic.

As a standard, font-weight: regular is the same as font-weight: 400 and font-weight: bold is the same as font-weight: 700

You may want to add font-weights like “Ultra Light” or “Black”. For these, you’ll need to look into the documentation of your font so you can match the font files with the correct font-weight number.

Step 4 (Optional): Using multiple custom fonts

You might be thinking… What do I do if I have more than 1 custom font?

For example, if I wanted to add the font Caviar Dreams AND the font Gilroy to my project.

For that, you’ll simply need to add more @font-face decelerations:

Step 5: Don’t forget about font-display

A quick note on performance.

This lets you decide how your web font will render depending on how long the fonts take to load.

The value you choose for font-display is of course up to you.

Using font-display: swap will mean there will always be a font shown to the user (i.e. they’ll never see a blank screen while the fonts load).

Take a look at this example on the BBC Sport website, who use font-display: swap :

(Note how the when the page loads, the font initially uses the fallback option Arial before loading their custom font ReithSans )

How to add font to css. Смотреть фото How to add font to css. Смотреть картинку How to add font to css. Картинка про How to add font to css. Фото How to add font to css

For a deeper dive into each of the font-display values, I’d recommend checking this article out from the Google Developers site.

Step 6: Styling your typography with CSS

We’re almost there!

So far we’ve added the cross-browser font files to our project, written out @font-face decelerations to reference our custom font files, and now it’s time to leverage the custom font into our typography.

By adding the @font-face declarations above, you’ve essentially added a new font that you can use when declaring font-family in your CSS.

I would just need to add the following CSS to my project:

Note that I’ve added Helvetica as a fallback font. This will be leveraged when the page is slow to load, as I added font-display: swap in step 5 above.

You now have custom fonts set up on your project 💪.

Want to become an advanced CSS & Sass developer?

Levelling up your CSS & Sass skills in 2021 is a great idea. Here’s why:

How to add font to css. Смотреть фото How to add font to css. Смотреть картинку How to add font to css. Картинка про How to add font to css. Фото How to add font to css

By Tom Ray, a front-end developer who lives in London with his fiancée and cat Arnold.

Want to become an advanced CSS & Sass developer?

Levelling up your CSS & Sass skills in 2021 is a great idea. Here’s why:

Источники информации:

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *