Type to generate UI components from text

OR

Browse thousands of MUI, Tailwind, React components that are fully customizable and responsive.

Explore Components

CSS Font Style for Great User Interaction: All You Need

People enjoy consuming quality content. The content on digital user interfaces frequently takes the form of written text. That means the visual presentation of any textual content is crucial to the success of a user interface. The textual arrangement and aesthetic look directly influence the overall quality of the user interface and user experience. Hence, choosing the right font involves understanding the advantages and limitations of each type.

CSS provides various text styling options/properties to enhance the users’ experience depending on the tone, look, reflection of professionalism, etc. Customizing these options lets us control the text presentation on a user interface.

This article will delve into in-depth CSS font styling techniques, exploring the different typefaces crucial to the development process and optimizing font performance.

On that note, you might want to consider visiting the purecode.ai marketplace to access over 10000+ AI-generated ready-made templates and components for your next project.

Essentials of CSS Font Styling

Understanding Fonts

A font is a resource file containing a graphical representation of characters such as alphabets, numbers, symbols, punctuation, and even emojis of a typeface. Each font represents a specific typeface with a particular weight, size, style, etc. However, some fonts share similar characteristics, enough to form a family of related fonts. The font choice is crucial for the visual experience and readability of the content of a digital interface. The following image shows a few examples:

A visual representation of different typeface from https://fontsource.org/.

Let us look at how to apply font styling to a single element.

<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Font variant</title>
    <style>
      body {
        height: 100vh;
        display: flex;
        align-items: center;
        justify-content: center;
      }

     h1 {
        font-size: 28px;
        color: blue;
        font-family: cursive;
      }
    </style>
  </head>
  <body>
    <h1>Styling a single text element</h1>
  </body>
</html>
A visual presentation of the regular cursive typeface.

From the code example above, applying the different font styles gave a blue h1 text in a regular cursive typeface.

To apply font styling to the whole page, give the body a font-family value, just as illustrated in the following example:

body {
  font-family: cursive;
}

Utilizing Font Shorthand in CSS

The CSS font property is a shorthand that combines multiple type-related properties of an element in a single declaration. The font property requires at least the size and family properties to work well. Without these, the system ignores the entire font property declaration. Also, the other values like styleweight, and variant must come before the size and family properties. Otherwise, the set optional properties use their default values instead.

The CSS font property syntax is as follows:

font: font-style font-variant font-weight font-size/line-height font-family;

Styling Fonts in CSS

CSS provides several properties for styling a typeface, these include the following:

  • font-family

  • font-style

  • font-weight

  • font color property

  • font-variant

Font family property

font family is a collection of fonts and their variations. The browser uses the font family to set the typeface the device will use to display the text. The font family property can hold multiple comma-separated font names, known as font stack as fallback fonts, to ensure maximum compatibility between browsers/operating systems. The browser will apply the fonts from left to right depending on their availability on the device the website or app is accessed. Consider the code example below:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Example of defining a font stack</title>
    <style>
      h1 {
        font-family: "Helvetica Neue", Helvetica, Arial, monospace, sans-serif;
        color: blue;
      }
    </style>
  </head>
  <body>
    <h1>Applying font family an element</h1>
  </body>
</html>
A visual presentation of the family property with a font stack value applied to a h1 element.

Font style property

This property is used to specify the typeface the browser will render. It accepts one of three value options:

  • normal

  • italic

  • Oblique

By default, the browser displays the normal-styled text. If an italic value is specified, the browser displays italic text if available. That is text with a slanted font face whose characters were modified to improve legibility. If the oblique value is specified instead, the browser displays slanted text using a simulated version of an italics font. However, if an italic value is set, but no italic face is available, the browser will try to simulate an italic text with oblique instead. The same applies to oblique; the browser will first look for an italics typeface.

Consider the following example:

<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>An example of the font styles</title>
    <style>
      h3 {
        font-family: "Helvetica Neue", Helvetica, Arial, monospace, sans-serif;
      }

      .normal {
        font-style: normal;
      }

      .italic {
        font-style: italic;
      }

      .oblique {
        font-style: oblique;
      }
    </style>
  </head>
  <body>
    <h3 class="normal">A normal text element</h3>
    <h3 class="italic">An italic text element</h3>
    <h3 class="oblique">An oblique text element</h3>
  </body>
</html>
A visual representation of the typeface styles applied to the different p tags.

Font weight property

This property defines the thickness of the font and specifies the degree of boldness of a text. The font weight accepts the following possible values:

  • normal

  • bold

  • bolder

  • lighter

  • numeric values

Numeric font-weight values are dependent on the typeface. Most times, these values may range from 400 to 700, where 400 is equivalent to normal and 700 to bold. However, some fonts have 800 and 900 inclusive, which depicts an even thicker font face.

The following code example shows how to use it:

<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Example of styling the weight</title>
    <style>
      p {
        font-family: Inter, BlinkMacSystemFont, "Segoe UI", sans-serif;
      }

      .normal {
        font-weight: normal;
      }

      .bold {
        font-weight: bold;
      }

      .bolder {
        font-weight: bolder;
      }

      .lighter {
        font-weight: lighter;
      }
    </style>
  </head>
  <body>
    <p class="normal">A normal text element</p>
    <p class="bold">An bold text element</p>
    <p class="bolder">An bolder or 800 weight text element</p>
    <p class="lighter">An lighter text element</p>
  </body>
</html>
A visual representation of the possible weight values.

Font color property

The CSS font color is a standalone attribute, that is used to set the foreground color value of a text. This property is used to organize elements and give meaning to text. The color property can accept any valid color unit, as illustrated in the following markup and CSS example:

<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Example of styling with the Color property</title>
  </head>
  <body>
    <h4 class="color">A normal color unit</h4>
  </body>
</html>

Below are different color units for styling a text blue.

 /* color: blue; */
 /* color: #3843bd; */
 /* color: rgb(56, 67, 189); */
 /* color: hsl(235, 54%, 48%); */

Font variant property

The font-variant is a CSS short-hand property used to set all the font variants of a text. A small-caps font variant converts all lowercase letters to uppercase letters. However, the effect of small caps causes the text to appear in a smaller font size than the original uppercase letters. Consider the following example:

<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Font variant</title>
    <style>
      body {
        height: 100vh;
        display: flex;
        align-items: center;
        justify-content: center;
      }

      h4 {
        font-family: "Helvetica Neue", Helvetica, Arial, monospace, sans-serif;
        font-variant: normal;
        /* font-variant: small-caps; */
      }
    </style>
  </head>
  <body>
    <h4>These are text variants</h4>
  </body>
</html>

Exploring Web Fonts

The previous sections discussed some essential CSS styling features. This section will explore web fonts and the different web fonts available.

Web fonts are fonts that are specifically designed and optimized for websites in an effort to improve the design and readability of content. CSS uses the @font-face to specify the font files available to be downloaded when a modern browser accesses a website. Using @font-face reduces the number of files requested and provides optimal compression. Next, let us discuss the different types of web fonts.

Types of Web Fonts

Based on their unique characteristics, fonts are classified into the following types:

  • Serif and san-serif fonts

  • Scripts fonts

  • Monospace fonts

  • Decorative fonts

Serif and san-serif fonts

Serif and sans-serif fonts make up the bulk of fonts on the web because they are readable and visually appealing. A serif font consists of small projections or strokes at the ends of each character, known as serif. These projections ensure serif fonts promote a sense of tradition and professionalism. Examples of serif fonts include Times New Roman, Play Fair, etc. On the other hand, sans is a French term that means without, emphasizing the lack of additional strokes or serifs. Sans-serif fonts offer a cleaner, more modern look. Examples of sans-serif fonts include Monserrat, Arial, etc.

Script fonts

Script fonts also known as cursive fonts, appear to be handwritten because they have fluid strokes. Scripts offer a lot of personality and elegance that promote familiarity with some digital user interfaces. However, the illegibility of script fonts makes them less suited as body text. Hence, designers employ scripts for creating logos, invitation cards, and other related materials. Examples include Pacifico, Tangerine, etc.

Monospace fonts

Monospace fonts consist of characters with a fixed width. Each character occupies the same horizontal spacing in a monospace font, making maintaining a consistent and visual text structure easier. Monospace fonts are preferable in code editors, windows terminals, etc. Examples of monospaced fonts include Courier, Monaco, and Consolas.

Decorative fonts

Decorative fonts also known as fantasy fonts, are a creative mix of standard typefaces intended to create unique and distinctive solutions. Unlike standard fonts that prioritize legible body text, decorative fonts are uniquely crafted for advertising because they evoke a specific theme or mood. Due to the creative nature and unique characteristics of decorative fonts, decorative fonts are a powerful tool in graphic and brand design. Examples include Phosphate, Chalkduster, etc.

Leveraging Online Font Services

Online font services are platforms that store and serve a variety of fonts that a website can easily integrate. All that is needed is to add a few lines of code to your HTML document to make everything work. The services that use this model include the following:

  • Google Fonts: Google Fonts is a completely free service that is commonly used because it is easy to use and includes over 700 font families.

  • Adobe Fonts: Adobe Fonts is a subscription-based font service that provides access to more than 20,000 font families.

  • Cloud typography fonts: Cloud.typography is a paid font hosting service that offers access to high-quality both cloud-hosted typography and self-hosted font files.

Embracing Variable Fonts

What are variable Fonts

Before variable fonts, the different font styles were in separate font files. However, in October 2016, the OpenType font variations, also known as variable font, were introduced as an extensive new technology. Variable font allows a typeface of multiple variations integrated into a single file. This feature is achieved by defining variations within the font, interpolated along one or more axes mainly width, and weight, but the type designer can specify others. Variable font ensures that web developers and companies can easily incorporate a font’s multiple variations into web infrastructures and devices with limited storage capacity. To learn more about variable fonts, check out the tutorial video below.

Next, let us look at how to use variable fonts in CSS.

Integrating Variable Fonts in CSS

Using a variable font involves declaring an @font-face in CSS that points to a single with all font variations. Below is a code example:

@font-face {
  font-family: 'Source Sans';
  src: url('/path_to/SourceSansVariable.woff2') format("woff2-variations");
  src: url('/path_to/SourceSans.woff2') format("woff2");
  font-weight: 400;
}

Note: You need a supporting browser to properly view the following example of variable font.

<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Variable fonts</title>
    <style>
      @font-face {
        font-family: "Source Sans";
        src: url("https://d33wubrfki0l68.cloudfront.net/f0f35e1c78339e9ab650f7d10a2b30af1ec0104a/147e5/assets/fonts/variable/sourcesansvariable-roman.ttf") format("truetype-variations");
        font-weight: 1 999;
      }

      .source-sans,
      .source-sans2,
      .source-sans3 {
        all: unset;
        display: block;
        text-align: center;
        font-family: "Source Sans";
        transition: all 0.45s ease-out;
      }

      .source-sans2 {
        font-weight: 500;
      }

      .source-sans3 {
        font-weight: 900;
      }

      .source-sans:hover,
      .source-sans2:hover {
        font-weight: 999;
      }

      .source-sans3:hover {
        font-weight: 200;
      }

      @media (min-width: 40em) {
        .source-sans,
        .source-sans2,
        .source-sans3 {
          font-size: 2.5rem;
        }
      }
    </style>
  </head>
  <body>
    <span class="source-sans">Well hello there Alligator</span>

    <span class="source-sans2">How are you doing</span>

    <span class="source-sans3 b30">Very well, thank you</span>
  </body>
</html>


From the visual presentation above, hovering over the different elements applies a weight variation of the source-sans variable font.

Differences between static fonts and variable fonts

Non-variable/Static fontsVariable fonts
Static fonts require separate files for each style.Variable fonts require the use of a single file to accommodate multiple styles.
Static fonts have fixed font styles and offer less flexibility.Variable fonts are flexible and allow for adjustment of font styles on the fly.
Multiple static fonts result in an increased page load time.Variable font enhances performance.
Static fonts do not support a smooth animation or transition effect.Variable fonts support smooth animation and transition between different font variations.
Static fonts are readily available for most fonts and font families.Variable fonts are limited in the choice of available font or font family.

Compatibility with Older Browsers

All modern browsers support variable fonts to an appreciable extent. However, to provide support for older browsers, you can choose to build your site with static fonts, and use variable fonts as a progressive enhancement:

/* Set up Roboto for old browsers, only regular + bold */
  @font-face {
    font-family: Roboto;
    src: url('Roboto-Regular.woff2');
    font-weight: normal;
  }

  @font-face {
    font-family: Roboto;
    src: url('Roboto-Bold.woff2');
    font-weight: bold;
  }

  body {
    font-family: Roboto;
  }

  .super-bold {
    font-weight: bold;
  }

/* Set up Roboto for modern browsers, all weights */
@supports (font-variation-settings: normal) {
  @font-face {
    font-family: 'Roboto';
    src: url('RobotoFlex-VF.woff2') format('woff2 supports variations'),
         url('RobotoFlex-VF.woff2') format('woff2-variations');
    font-weight: 100 1000;
    font-stretch: 25% 151%;
  }

  .super-bold {
    font-weight: 1000;
  }
}

Optimizing Font Performance with CSS

It is vital to think about the fonts you want to use. While using multiple fonts on the UI may be aesthetically pleasing, it can impact a page’s load time. Also, heavy font files have a negative impact on performance.

The following sub-sections discuss a few useful methods to optimize font performance.

Efficient Font Loading

It is crucial to use font-loading strategies to prevent fonts from slowing down page load. By default, the browser loads a font only when applied to an element using the font-family property, not when the stylesheet first referenced the font using the @font-face rule. Therefore, it can be beneficial to use rel=”preload” to load vital fonts to make them readily available when needed:

<link
  rel="preload"
  href="OpenSans-Regular-webfont.woff2"
  as="font"
  type="font/woff2"
  crossorigin 
/>

Loading Only Necessary Glyphs

It involves specifying a subset of glyphs the browser should download when it is hard to be sure of the glyphs the browser will use in the content. The developer achieves this by creating a font file containing the required subset or specifying a glyph subset using the unicode-range @font-face descriptor. This process is known as glyph subsetting. This method can significantly reduce the file size and enhance page loading speed. Below is a code example to illustrate how to achieve this feature in CSS.

@font-face {
  font-family: "Open Sans";
  src: url("OpenSans-Regular-webfont.woff2") format("woff2");
  unicode-range: U+0025-00FF;
}

Configuring Font Display Behavior

When applied to the @font-face rule, the font-display descriptor specifies how the browser handles font loading. This method allows the browser to render a fallback font while the font loads or fails to load. This method improves performance and user experience by making the text visible instead of a blank screen while the text loads.

@font-face {
  font-family: yourType;
  src: url(/path_to_fonts/yourType.woff) format("woff");
  font-weight: 400;
  font-display: fallback;
}

Final Notes

We covered the essential text styling techniques and how to use this knowledge to customize content on a webpage. We also explored the different typeface variations and how to utilize them to achieve optimal results that won’t impact the performance and readability of content. As such, it is crucial to recognize how text styling in CSS is critical to web development and user experience and how we can leverage it to achieve an interactive, engaging, and dynamic user interface.

To quickly customize and control the visual presentation of your text contents, visit us at purecode.ai.

Recommended Resources

If you enjoyed this article, consider reading other articles from our blog:

Ofili Chukwuemeka Timothy

Ofili Chukwuemeka Timothy