CSS

font-family


In CSS, the font-family property is used to specify the font for an element. This property can accept a comma-separated list of font family names and/or generic family names. The browser will use the first available font in the list. Here's a basic example of how to use font-family in CSS:

body {
    font-family: "Helvetica Neue", Arial, sans-serif;
}

In this example:

  • "Helvetica Neue" is the preferred font.
  • If "Helvetica Neue" is not available, the browser will try to use Arial.
  • If neither of those fonts is available, the browser will use a default sans-serif font.

 

Generic Font Families

CSS defines five generic font families:

  • serif - Fonts with small lines or embellishments at the ends of strokes.
  • sans-serif - Fonts without those embellishments.
  • monospace - Fonts in which each character occupies the same width.
  • cursive - Fonts that mimic handwriting.
  • fantasy - Decorative fonts.

 

Example Usage

Here's how you might define styles for different elements using various font families:

h1 {
    font-family: "Times New Roman", Times, serif;
}

p {
    font-family: Georgia, serif;
}

code {
    font-family: "Courier New", Courier, monospace;
}

blockquote {
    font-family: "Lucida Handwriting", "Comic Sans MS", cursive;
}

 

Fallback Fonts

It's important to include fallback fonts in case the preferred font is not available. Fallback fonts ensure that the text is displayed in a readable manner even if the desired font cannot be loaded.

 

Custom Fonts

You can also use custom fonts by importing them using @font-face or linking to a font service like Google Fonts. Here's an example of using Google Fonts:

  1. Link to the Google Font in your HTML file:
<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;700&display=swap" rel="stylesheet">
  1. Use the font in your CSS:
body {
    font-family: 'Roboto', sans-serif;
}

 

@font-face Rule

To define a custom font using the @font-face rule:

@font-face {
    font-family: 'MyCustomFont';
    src: url('mycustomfont.woff2') format('woff2'),
         url('mycustomfont.woff') format('woff');
}

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

In this example, mycustomfont.woff2 and mycustomfont.woff are the font files you want to use. The browser will choose the appropriate format it supports.

By understanding and using the font-family property effectively, you can greatly enhance the typography and overall design of your web pages.