Explain Codes LogoExplain Codes Logo

Google fonts URL break HTML5 Validation on w3.org

html
responsive-design
best-practices
web-development
Anton ShumikhinbyAnton Shumikhin·Sep 30, 2024
TLDR

To resolve HTML5 validation errors related to Google Fonts URLs, switch & with &. For instance, ?family=Open+Sans&Roboto becomes ?family=Open+Sans&Roboto. This alteration makes sure your font links stay active and valid.

Improved Example:

<!-- Web developers always use protection --> <link href="https://fonts.googleapis.com/css?family=Open+Sans&amp;Roboto" rel="stylesheet">

For maintaining valid URLs, URL encoding of special characters like | to %7C is paramount. An impeccably formatted URL would look like:

Refactored URL:

<link href="https://fonts.googleapis.com/css?family=Open+Sans:400,600,300,800,700,400italic%7CPT+Serif:400,400italic%7CBree+Serif" rel="stylesheet">

To prevent HTML5 validation breaches, URL encoding of every unique character is mandatory. Visit "http://www.utf8-chartable.de/" for encoding guidelines.

Common Mistakes and Solutions

Beware of Characters

UTF-8 encoding problems occur in URL construction. Non-standard characters like spaces or punctuation marks need proper encoding, e.g., a space can be encoded as %20 or replaced with +.

Stay Updated

Remember, HTML5 validators can change policies. Your previously valid code might fail now. Regular monitoring of the validator's changelog and community forums is advisable.

A Bonus

Robust URL encoding not only compliance with HTML5 standards but also boosts your website security and web font loading speed.

Alternative Ways Out

If URL encoding seems tricky, split the Google Fonts URL into multiple link elements. Here is how:

<!-- Sending fonts to rehab - They say 'no', code says 'yes' --> <link href="https://fonts.googleapis.com/css?family=Open+Sans:400,600,300,800,700,400italic" rel="stylesheet"> <link href="https://fonts.googleapis.com/css?family=PT+Serif:400,400italic" rel="stylesheet"> <link href="https://fonts.googleapis.com/css?family=Bree+Serif" rel="stylesheet">

Utilize CSS @import

Use @import in your stylesheet as another solution. For example:

/* Importing fonts. Not beers unfortunately. */ @import url('https://fonts.googleapis.com/css?family=Open+Sans:400,600,300,800,700,400italic'); @import url('https://fonts.googleapis.com/css?family=PT+Serif:400,400italic'); @import url('https://fonts.googleapis.com/css?family=Bree+Serif');

Keep your CSS links sleek and efficient for both looks and performance.