Peter Grassberger

Web Development, Digital Politics and Media, Participation, Pirate.
27.06.2014

Style Links By hreflang

or how to mark links with a different language.

I've been using the hreflang tag for some time now to mark links that point to websites with content in different languages. It's nice to have this kind of semantic information, but no browser displays links any different based on it. I like the way Wikipedia marks its external links with an icon and I wanted something similar for my petergrassberger.com and petergrassberger.at sites. I found something on Lachy's Log: Handy CSS that was almost what i wanted, take a look at the final version below or as a gist.

index.html:
<!doctype html>
<html lang="en"><!-- or "de" -->
    <head>
        <meta charset="utf-8" />
        <title>Style links by hreflang</title>
    </head>
    <body>
        <!-- this link will have "de" appended -->
        <a href="https://petergrassberger.at/" hreflang="de">German Site</a>
        <!-- this link will stay the same because the site lang is "en" -->
        <a href="https://petergrassberger.com/" hreflang="en">English Site</a>
    </body>
</html>
style.css:
/* shows hreflang that are not "en" after links on a lang="en" site */
html[lang="en"] :link[hreflang]:not([hreflang="en"])::after {
    content: " "attr(hreflang);
    font-size: xx-small;
}
/* shows hreflang that are not "de" after links on a lang="de" site */
html[lang="de"] :link[hreflang]:not([hreflang="de"])::after {
    content: " "attr(hreflang);
    font-size: xx-small;
}

/*
    add more if you have more languages
*/

The html[lang="en"] part filters all the pages of other languages, then [hreflang] checks if the hreflang-attribute exists and [hreflang="en"] checks if the hreflang-attribute has a different value from en. The ::after selector appends content to the :link-elements and content: says what to append, in this case one white space character and the value of the hreflang-attribute.

It is a shame that there is no way (that I know of) to compare the html lang attribute directly with the a hreflang attribute, because then you could reduce the css to only one selector and you wouldn't have to add each language separately. Alternatively you could also do this with javascript (and jQuery).

How did you like this post?

Feel free to send your thoughts on Twitter or via E-Mail.