Implementing Custom Fonts and Advanced Typography in CSS
Explore how to implement custom fonts in CSS using the @font-face rule and variable fonts. Understand font-display options to optimize loading and apply advanced typography properties like text-indent, text-transform, and text-shadow to enhance web page visuals.
In this lesson, we’ll focus on loading custom fonts using @font-face and exploring advanced font features. By incorporating custom typefaces, we can enhance the visual identity of our web projects.
Loading custom fonts in stylesheets
The @font-face rule allows us to define custom fonts to be used in our stylesheets. We specify the font's name and the source file.
/* Loading a Custom Font */@font-face {font-family: 'OpenSans';src: url('fonts/OpenSans-Regular.woff2') format('woff2'),url('fonts/OpenSans-Regular.woff') format('woff');font-weight: normal;font-style: normal;font-display: swap;}
In the above code:
Line 2: We name the custom font
OpenSans.Lines 3–4: We provide the URLs to the font files in different formats for broader browser support.
Line 5–6: We specify the font weight and style.
Line 7: We use
font-display: swapto control how the font loads and displays.
Variable fonts
Variable fonts contain multiple styles in a single file, reducing the number of font files needed.
@font-face {font-family: 'RobotoFlex';src: url('fonts/RobotoFlex-VariableFont.ttf') format('truetype-variations');font-weight: 100 900;}