Explain Codes LogoExplain Codes Logo

How to Apply a Global Font to the Whole HTML Document

html
responsive-design
css
font-properties
Anton ShumikhinbyAnton Shumikhin·Nov 5, 2024
TLDR

Set a universal font using CSS with the font-family property at the root level html:

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

This way, 'Roboto' becomes the default font for your entire document, offering consistent text styling.

Enhance this uniformed look by combining font-family with font-size and color properties, then apply the !important keyword to override any other styles:

* { font-family: 'Roboto', sans-serif !important; font-size: 16px !important; color: #333 !important; }

Default font size and scalability

In addition to setting a universal font, you can set a baseline font-size at the body level for scalability and usability. Use relative units such as rem or em:

body { font-size: 1rem; /* Set default font size */ }

This provides a flexible foundation for defining sizes of other elements in relation to the base font size.

Backup fonts for consistent experience

When defining your font-family, always include fallback fonts in a font stack. This ensures that if the primary font fails to load, an alternative font is used, maintaining a uniform look:

html { font-family: 'Open Sans', 'Arial', sans-serif; }

With this setup, 'Open Sans' is your primary font, and 'Arial' or a generic sans-serif act as backup fonts.

Overriding default styles

For certain elements, you may need to override default settings for visual hierarchy or branding purposes. Use specific selectors and the !important directive to achieve this, but sparingly to avoid blocking the natural cascading flow of CSS:

h1 { font-family: 'Georgia', serif !important; font-size: 2rem !important; /* Because size matters */ }

Adapting font-size for different screens

Employ media queries to implement responsive typography, ensuring your text remains legible on different screen sizes:

@media (max-width: 768px) { html { font-size: 14px; /* For smaller screens; "Honey, I shrunk the font!" */ } } @media (min-width: 769px) { html { font-size: 16px; /* Bigger screens get bigger fonts; "Fontzilla attack!" */ } }

Font property speed run

Use the font shorthand property to set font-style, font-variant, font-weight, font-size/line-height, and font-family conveniently and swiftly in a single line:

body { font: 400 1rem/1.5 'Roboto', sans-serif; /* Because who has time to write all those out? */ }

This essentially sets all body text to 'Roboto' font with a 1rem size and 1.5 line-height.