Premium CSS Course

CSS Fonts

Fonts are a critical part of web design, affecting the readability, hierarchy, and overall look of a website. CSS offers several properties to control fonts on a web page, including font-family, font-size, font-style, and font-weight.

Font Family

The font-family property allows you to specify which font(s) to use for text in an element. You can define a list of fonts, starting with the preferred font and ending with a generic font family as a fallback in case the preferred font is unavailable.


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

In the example above, the browser will first try to use the "Arial" font. If it's unavailable, it will fall back to any available sans-serif font.

Generic Font Families

Font Size

The font-size property is used to define the size of the text. It can be specified in various units, such as pixels (px), ems (em), percentages (%), and rems (rem).


        h1 {
            font-size: 36px;
        }
    

In this example, the font size of the <h1> element will be set to 36 pixels. The em and rem units are relative to the parent element’s font size and the root element’s font size, respectively.

Common Units for Font Size

Font Style

The font-style property allows you to control the style of the font, such as normal, italic, or oblique.


        p {
            font-style: italic;
        }
    

This will make all <p> elements italicized.

Font Style Options

Font Weight

The font-weight property allows you to adjust the thickness of the text. You can use numeric values (100 to 900) or predefined values such as normal and bolder.


        h2 {
            font-weight: bold;
        }
    

This will make all <h2> elements bold. Numeric values for font weight range from 100 (lightest) to 900 (boldest), with 400 being the default for normal text.

Common Font Weight Values

Font Variants

You can also use the font-variant property to specify small-caps or other font variations.


        h3 {
            font-variant: small-caps;
        }
    

This will display all <h3> text in small caps, regardless of the original case of the text.

Web Fonts

Web fonts allow you to use custom fonts on your website by linking to external font services like Google Fonts or using the @font-face rule. Here’s an example using Google Fonts:


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

This will load the "Roboto" font from Google Fonts and apply it to the body of the page.

Best Practices for Font Usage