OneBite.Dev - Coding blog in a bite size

use custom fonts css

Code snippet for how to use custom fonts css with sample and detail explanation

Use Custom Fonts with CSS

In the world of web design, typography is a crucial aspect that shapes the aesthetics and readability of your content. CSS, being an essential tool for web styling, enables you to incorporate custom fonts on your website beyond the basic preset ones. This article guides you through a step-by-step tutorial on how to use custom fonts with CSS.

Code Snippet

@font-face {
  font-family: 'MyCustomFont';
  src: url('MyCustomFont.eot'); /* IE9 Compat Modes */
  src: url('MyCustomFont.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */
       url('MyCustomFont.woff2') format('woff2'), /* Super Modern Browsers */
       url('MyCustomFont.woff') format('woff'), /* Pretty Modern Browsers */
       url('MyCustomFont.ttf')  format('truetype'), /* Safari, Android, iOS */
       url('MyCustomFont.svg#svgFontName') format('svg'); /* Legacy iOS */
}
body {
  font-family: 'MyCustomFont', Fallback, sans-serif;
}

Code Explanation

The @font-face at-rule allows custom fonts to be loaded on a webpage.

The font-family property within the @font-face at-rule is used to name a custom font. A unique, spot-on name is ideal for the font-family as you would use it in the rest of your CSS file.

The src property indicates the URL(s) where the custom font can be found. Each URL points to a .eot, .woff2, .woff, .ttf or .svg file that represents a font format. The browser will download and use the first format it supports. These different file types are for browser compatibility.

The url('font.woff') format('woff') line explains to the browser where to find the web font file, what format it is in and what to do with it.

body {
  font-family: 'MyCustomFont', Fallback, sans-serif;
}

And lastly, you can use your custom font on elements of your choice by specifying your custom font’s name in the font-family property. ‘Fallback’ is an optional generic font family, serving as a back-up if ‘MyCustomFont’ fails to load.

That’s all there is to it. You can now use your custom fonts in CSS and stand out from the crowd with your unique typography.

css