- CSS Web Fonts
- Different Font Formats
- Browser Support for Font Formats
- Using The Font You Want
- Example
- Using Bold Text
- Example
- CSS Font Descriptors
- Подключение шрифтов в CSS
- Локальные шрифты
- Форматы шрифтов
- Разные начертания шрифтов
- Обычный:
- How to import fonts in CSS?
- 6 Answers 6
- Using custom fonts using CSS?
- 8 Answers 8
- Linked
- Related
- Hot Network Questions
- Subscribe to RSS
CSS Web Fonts
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/OTF | 9.0* | 4.0 | 3.5 | 3.1 | 10.0 |
WOFF | 9.0 | 5.0 | 3.6 | 5.1 | 11.1 |
WOFF2 | 14.0 | 36.0 | 39.0 | 10.0 | 26.0 |
SVG | Not supported | Not supported | Not supported | 3.2 | Not supported |
EOT | 6.0 | Not supported | Not supported | Not supported | Not 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:
Descriptor | Values | Description |
---|---|---|
font-family | name | Required. Defines a name for the font |
src | URL | Required. Defines the URL of the font file |
font-stretch | normal condensed ultra-condensed extra-condensed semi-condensed expanded semi-expanded extra-expanded ultra-expanded | Optional. Defines how the font should be stretched. Default is «normal» |
font-style | normal italic oblique | Optional. Defines how the font should be styled. Default is «normal» |
font-weight | normal bold 100 200 300 400 500 600 700 800 900 | Optional. Defines the boldness of the font. Default is «normal» |
unicode-range | unicode-range | Optional. Defines the range of UNICODE characters the font supports. Default is «U+0-10FFFF» |
Подключение шрифтов в CSS
Если не вникать в подробности, по быстрому подключить шрифт можно так:
/* Обычный */ @font-face < font-family: 'FontName'; src: url(/fonts/font.ttf); >/* Жирный */ @font-face < font-family: 'FontName bold'; src: url(/fonts/font-bold.ttf); >.text-1 < font-family: 'FontName'; font-size: 20px; >.text-2
Такой метод вполне работает в большинстве браузеров, но неверен. В данном примере упущено:
- Нет названия шрифта в свойстве local .
- Подключен только один формат шрифта.
- Неправильно настроены начертания.
Локальные шрифты
Правило @font-face src позволяет задать название локального шрифта, т.е. если у пользователя на компьютере уже установлен нужный шрифт, то будет использоваться именно он, при этом существенно увеличится скорость загрузки и отрисовки страницы.
Можно указать несколько названий:
Форматы шрифтов
Сегодня используются четыре формата, рассмотрим их подробнее:
TTF/OTF – работают в большинстве браузеров, кроме IE.
EOT – создан Microsoft, представляет сжатую копию шрифта TTF, поддерживается только в IE.
WOFF – формат представляет собой сжатый шрифт в формате TTF/OTF.
WOFF2 – имеет улучшенное сжатие, по сравнению с первой версией.
Как видно нет единого формата, который поддерживается всеми браузерами, поэтому нужно делать подключение нескольких файлов, браузер сам выберет подходящий формат. Рекомендуется подключать файлы шрифтов по приоритету:
- WOFF2 для современных браузеров.
- WOFF для браузеров, которые не поддерживают WOFF2.
- TTF для устаревших браузерах
- EOT для поддержки IE.
Если в наборе есть не все форматы, их можно получить перекодировкой с помощью сервисов onlinefontconverter.com или convertio.co.
Разные начертания шрифтов
Пример подключения шрифта «Crimson Text» в разных начертаниях:
Обычный:
How to import fonts in CSS?
I want to use some fonts and I want it to work without having this font on the client computer. I have done this but it doesn’t work:
6 Answers 6
Following lines are used to define a font in css
Following lines to define/use the font in css
Highly recommend fontsquirrel.com/tools/webfont-generator for converting fonts for web and generating the CSS.
One of the best source of information on this topic is Paul Irish’s Bulletproof @font-face syntax article.
Read it and you will end with something like:
/* definition */ @font-face < font-family: EntezareZohoor2; src: url('fonts/EntezareZohoor2.eot'); src: url('fonts/EntezareZohoor2.eot?') format('☺'), url('fonts/EntezareZohoor2.woff') format('woff'), url('fonts/EntezareZohoor2.ttf') format('truetype'); font-weight: normal; font-style: normal; >/* use */ body
When I went to Google fonts all they gave me were true type font files .ttf and didn’t explain at all how to use the @font-face to include them into my document. I tried the web font generator from font squirrel too, which just kept running the loading gif and not working. I then found this site —
I had great success using the following method:
I selected the Add Fonts button, leaving the default options, added all of my .ttf that Google gave me for Open Sans (which was like 10, I chose a lot of options. ).
Then I selected the Convert button.
Heres the best part!
They gave me a zip file with all the font format files I selected, .ttf , .woff and .eot . Inside that zip file they had a demo.html file that I just double clicked on and it opened up a web page in my browser showing me example usages of all the different css font options, how to implement them, and what they looked like etc.
I still didn’t know at this point how to include the fonts into my stylesheet properly using @font-face but then I noticed that this demo.html came with it’s own stylesheet in the zip as well. I opened the stylesheet and it showed how to bring in all of the fonts using @font-face so I was able to quickly, and easily, copy paste this into my project —
@font-face < font-family: 'Open Sans'; src: url('fonts/Open_Sans/OpenSans-BoldItalic.eot'); src: url('fonts/Open_Sans/OpenSans-BoldItalic.eot?#iefix') format('embedded-opentype'), url('fonts/Open_Sans/OpenSans-BoldItalic.woff') format('woff'), url('fonts/Open_Sans/OpenSans-BoldItalic.ttf') format('truetype'); font-weight: bold; font-style: italic; >@font-face < font-family: 'Open Sans'; src: url('fonts/Open_Sans/OpenSans-LightItalic.eot'); src: url('fonts/Open_Sans/OpenSans-LightItalic.eot?#iefix') format('embedded-opentype'), url('fonts/Open_Sans/OpenSans-LightItalic.woff') format('woff'), url('fonts/Open_Sans/OpenSans-LightItalic.ttf') format('truetype'); font-weight: 300; font-style: italic; >@font-face < font-family: 'Open Sans'; src: url('fonts/Open_Sans/OpenSans-SemiBold.eot'); src: url('fonts/Open_Sans/OpenSans-SemiBold.eot?#iefix') format('embedded-opentype'), url('fonts/Open_Sans/OpenSans-SemiBold.woff') format('woff'), url('fonts/Open_Sans/OpenSans-SemiBold.ttf') format('truetype'); font-weight: 600; font-style: normal; >@font-face < font-family: 'Open Sans'; src: url('fonts/Open_Sans/OpenSans-Regular.eot'); src: url('fonts/Open_Sans/OpenSans-Regular.eot?#iefix') format('embedded-opentype'), url('fonts/Open_Sans/OpenSans-Regular.woff') format('woff'), url('fonts/Open_Sans/OpenSans-Regular.ttf') format('truetype'); font-weight: normal; font-style: normal; >@font-face < font-family: 'Open Sans'; src: url('fonts/Open_Sans/OpenSans-Light.eot'); src: url('fonts/Open_Sans/OpenSans-Light.eot?#iefix') format('embedded-opentype'), url('fonts/Open_Sans/OpenSans-Light.woff') format('woff'), url('fonts/Open_Sans/OpenSans-Light.ttf') format('truetype'); font-weight: 300; font-style: normal; >@font-face < font-family: 'Open Sans'; src: url('fonts/Open_Sans/OpenSans-Italic.eot'); src: url('fonts/Open_Sans/OpenSans-Italic.eot?#iefix') format('embedded-opentype'), url('fonts/Open_Sans/OpenSans-Italic.woff') format('woff'), url('fonts/Open_Sans/OpenSans-Italic.ttf') format('truetype'); font-weight: normal; font-style: italic; >@font-face < font-family: 'Open Sans'; src: url('fonts/Open_Sans/OpenSans-SemiBoldItalic.eot'); src: url('fonts/Open_Sans/OpenSans-SemiBoldItalic.eot?#iefix') format('embedded-opentype'), url('fonts/Open_Sans/OpenSans-SemiBoldItalic.woff') format('woff'), url('fonts/Open_Sans/OpenSans-SemiBoldItalic.ttf') format('truetype'); font-weight: 600; font-style: italic; >@font-face < font-family: 'Open Sans'; src: url('fonts/Open_Sans/OpenSans-ExtraBold.eot'); src: url('fonts/Open_Sans/OpenSans-ExtraBold.eot?#iefix') format('embedded-opentype'), url('fonts/Open_Sans/OpenSans-ExtraBold.woff') format('woff'), url('fonts/Open_Sans/OpenSans-ExtraBold.ttf') format('truetype'); font-weight: 800; font-style: normal; >@font-face < font-family: 'Open Sans'; src: url('fonts/Open_Sans/OpenSans-ExtraBoldItalic.eot'); src: url('fonts/Open_Sans/OpenSans-ExtraBoldItalic.eot?#iefix') format('embedded-opentype'), url('fonts/Open_Sans/OpenSans-ExtraBoldItalic.woff') format('woff'), url('fonts/Open_Sans/OpenSans-ExtraBoldItalic.ttf') format('truetype'); font-weight: 800; font-style: italic; >@font-face < font-family: 'Open Sans'; src: url('fonts/Open_Sans/OpenSans-Bold.eot'); src: url('fonts/Open_Sans/OpenSans-Bold.eot?#iefix') format('embedded-opentype'), url('fonts/Open_Sans/OpenSans-Bold.woff') format('woff'), url('fonts/Open_Sans/OpenSans-Bold.ttf') format('truetype'); font-weight: bold; font-style: normal; >
The demo.html also had it’s own inline stylesheet that was interesting to take a look at, though I am familiar with working with font weights and styles once they are included so I didn’t need it much. For an example of how to implement a font style onto an html element for reference purposes you could use the following method in a similar case to mine after @font-face has been used properly —
html, body < margin: 0; font-family: 'Open Sans'; >.banner h1 < font-size: 43px; font-weight: 700; >.banner p
Using custom fonts using CSS?
I’ve seen some new websites that are using custom fonts on their sites (other than the regular Arial, Tahoma, etc.). And they support a nice amount of browsers. How does one do that? While also preventing people from having free access to download the font, if possible.
8 Answers 8
Generically, you can use a custom font using @font-face in your CSS. Here’s a very basic example:
Then, trivially, to use the font on a specific element:
( .classname is your selector).
Note that certain font-formats don’t work on all browsers; you can use fontsquirrel.com’s generator to avoid too much effort converting.
You can find a nice set of free web-fonts provided by Google Fonts (also has auto-generated CSS @font-face rules, so you don’t have to write your own).
while also preventing people from having free access to download the font, if possible
Nope, it isn’t possible to style your text with a custom font embedded via CSS, while preventing people from downloading it. You need to use images, Flash, or the HTML5 Canvas, all of which aren’t very practical.
Thank you for the great detailed answer. May I ask if that kind of approach works for the older browsers as well? Such as.. IE8/7/6? And by the way, are all of the fonts displayed on Google Webfonts free for commercial use?
@Don @font-face works with all reasonably-new browsers, but you need to have the right formats; that’s why I recommended using fontsquirrel.com to automate the process of conversion and rule-generation. And yes, Google Webfonts are free for commercial use (little link for more info).
@Chris, Is omitting the font-style: and font-weight: in your @font-face declaration violating any standards?
To make sure that your font is cross-browser compatible, make sure that you use this syntax:
You have to download the font file and load it in your CSS.
F.e. I’m using the Yanone Kaffeesatz font in my Web Application.
Today there are four font container formats in use on the web: EOT, TTF, WOFF, and WOFF2.
Unfortunately, despite the wide range of choices, there isn’t a single universal format that works across all old and new browsers:
- EOT is IE only,
- TTF has partial IE support,
- WOFF enjoys the widest support but is not available in some older browsers
- WOFF 2.0 support is a work in progress for many browsers.
If you want your web app to have the same font across all browsers then you might want to provide all 4 font type in CSS
Hi Hitesh. May I ask what is the use of #iefix ? and this part font-family: ‘besom’; !important , the !important is outside the ; ?
If you dont find any fonts that you like from Google.com/webfonts or fontsquirrel.com you can always make your own web font with a font you made.
Although im not sure about preventing someone from downloading your font.
there’s also an interesting tool called CUFON. There’s a demonstration of how to use it in this blog It’s really simple and interesting. Also, it doesn’t allow people to ctrl+c/ctrl+v the generated content.
I am working on Win 8, use this code. It works for IE and FF, Opera, etc. What I understood are : woff font is light et common on Google fonts.
Go here to convert your ttf font to woff before.
First of all, you can’t prevent people from downloading fonts except if it is yours and that usually takes months. And it makes no sense to prevent people from using fonts. A lot of fonts that you see on websites can be found on free platforms like the one I mentioned below.
But if you want to implement a font into your website read this: There is a pretty simple and free way to implement fonts into your website. I would recommend Google fonts because it is free and easy to use. For example, I’ll use the Bangers font from Google.(https://fonts.google.com/specimen/Bangers?query=bangers&sidebar.open&selection.family=Bangers) This is how it would look like: HTML
Linked
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.7.24.43543
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.