The @font-face CSS rule | CSS Selectors, Typography and More

The @font-face rule allows you to customize the fonts used on your website. You can import custom fonts from external sources or define them directly within your stylesheet.

Basic Syntax

CSS

@font-face {

  font-family: ‘MyCustomFont’;

  src: url(‘path/to/font.woff2’) format(‘woff2’),

       url(‘path/to/font.woff’) format(‘woff’);

}

Key Properties

  • font-family: Defines the name of the font.
  • src: Specifies the URL of the font file and its format. Common formats include woff, woff2, ttf, eot, and svg.

Using Custom Fonts

  1. Obtain the font files: Download the font files from the font provider.
  2. Upload the files: Upload the font files to your web server.
  3. Define the font: Use the @font-face rule to define the font family and specify the URL of the font files.
  4. Apply the font: Use the font-family property to apply the custom font to your elements.

Example

HTML

<link rel=”stylesheet” href=”styles.css”>

CSS

@font-face {

  font-family: ‘MyCustomFont’;

  src: url(‘fonts/myfont.woff2’) format(‘woff2’),

       url(‘fonts/myfont.woff’) format(‘woff’);

}

body {

  font-family: ‘MyCustomFont’, sans-serif;

}

Best Practices

  • Choose appropriate formats: Use modern formats like woff2 and woff for better performance and compatibility.
  • Optimize font files: Use tools to compress and optimize font files to reduce their size.
  • Consider licensing: Ensure you have the necessary license to use the font commercially.
  • Fallback fonts: Provide a fallback font family in case the custom font is not supported.

By using the @font-face rule, you can customize the typography on your website and create a unique and visually appealing design. Remember to choose fonts that are appropriate for your target audience and ensure they are optimized for performance and compatibility.

Web typography | CSS Selectors, Typography and More
Variable fonts | CSS Selectors, Typography and More

Get industry recognized certification – Contact us

keyboard_arrow_up
Open chat
Need help?
Hello 👋
Can we help you?