Using @font-face in CSS

Abhay Jain
2 min readDec 13, 2020

--

The @font-face feature from CSS3 allows us to use custom typefaces on the web in an accessible, manipulable, and scalable way.

Why use @font-face if we have Cufon, sIFR, and using text in images?

A few benefits of leveraging @font-face for custom fonts:

  • Full searchability by Find (ctrl-F)
  • Accessibility to assistive technologies like screen readers
  • Text is translatable, through in-browser translation or translation services
  • CSS has full ability to tweak the typographical display: line-height, letter-spacing, text-shadow, text-align, and selectors like ::first-letter and ::first-line.

Add @font-face in project

At its most basic, we declare a new custom remote font to be used like so:

@font-face {
font-family: 'Tagesschrift';
src: url('tagesschrift.ttf');
}

Then put it to use:

h1, h2, h3 { font-family: 'Tagesschrift', 'Georgia', serif; }

In this @font-face declaration, we’re using the font-family property to explicitly name the font. It can be anything, regardless of what the font is actually called; font-family: 'SuperDuperComicSans'; would work out just fine, though perhaps not for your reputation. In the src property we point to where the browser can find the font asset. Depending on the browser, some valid font types are eot, ttf, otf, svg, or a data URI embedding the entire font data inline.

Of course, nothing is ever as simple as it should be. The initial limitation of the above code was that it did not serve an EOT to IE 6–8.

@font-face {
font-family: 'Tagesschrift';
src: url('tagesschrift.eot'); /* IE 5-8 */
src: local('☺'), /* sneakily trick IE */
url('tagesschrift.woff') format('woff'), /* FF 3.6, Chrome 5, IE9 */
url('tagesschrift.ttf') format('truetype'), /* Opera, Safari */
url('tagesschrift.svg#font') format('svg'); /* iOS */
}

Summary

Webfonts deliver quite a bit of freedom to designers and with upcoming features like discretionary ligatures and stylistic alternates, they will have a lot more flexibility. For now, you can feel confident implementing this part of CSS3 as it covers 98% of deployed browsers.

--

--

Abhay Jain
Abhay Jain

Written by Abhay Jain

Developer with 3 yrs of industrial experience in developing scalable web applications.