The HTML lang attribute: check if you have been using it correctly

I have decided to write this post to explain a small and important update I have made to the layout structure.

As I have written this post in English I have had to update the layout structure and set language values correctly: pt-br for Portuguese sections and en for English content.

For this, I used the gatsby-plugin-html-attributes to define the language on the <html> element, and I included a new attribute into each post frontmatter section so that I could use it to specify the language the articles are written in.

W3C recommeds always using lang on the <html> tag to define the default language of the text on the page. It is important to use it on the <html> rather than on the <body> because the first also covers text content inside the <head> element.

In my case, I set <html lang="pt-br"> as the main site language and included lang="en" in the content wrapper div of English articles.

It is also possible to use the :lang() pseudo-class selector to style content in different languages. Although the most common use cases are associated with text direction, such as right-to-left texts, we can use other properties as in this example:

  p:lang(es) {
    background: #ffd2d2;
  }
  p:lang(es)::before {
    content: '🇪🇸';
  }

  p:lang(pt-br) {
    background: #fffbc7;
  }
  p:lang(pt-br)::before {
    content: '🇧🇷';
  }

  p:lang(en) {
    background: #dcf8ff;
  }
  p:lang(en)::before {
    content: '🇬🇧';
  }

"El mundo era tan reciente, que muchas cosas carecían de nombre, y para mencionarlas había que señalarlas con el dedo."
Cien Años de Soledad

"O mundo era tão recente que muitas coisas careciam de nome e para mencioná-las se precisava de apontar com o dedo."
Cem Anos de Solidão

"The world was so recent that many things lacked names, and in order to indicate them it was necessary to point."
One Hundred Years of Solitude

Reinaldo Ferraz, a friend of mine, says that alt and lang are two simple yet powerful HTML attributes; however their use is sometimes neglected. I highly recommend watching his presentation about these attributes, where he shows their impact not only on accessibility but also on page optimization for search engines (SEO).

When I worked for the W3C Brazil office and Ceweb at NIC.br, I had the pleasure of working with Reinaldo, who knows every technical detail related to web accessibility and who, by the way, has recently published a new book on this subject and its portuguese version is available on Amazon.

I thought it would be nice to share this small update because we seldom give proper attention to this simple attribute.


Newton Calegari
💻 Product Manager | 📚 CS & Design Professor
@newtoncalegari