Show title attribute when using abbr element
I had a request from an international client to change the way the current site location was being shown. They have an office in Asia Pacific, which is also known as APAC for short. On smaller screens they wanted to use the abbreviation while on larger screens then wanted the full title.
One approach that you see many Frameworks use would be <span class="show-on-mobile">APAC</span><span class="hide-on-mobile">Asia Pacific</span>
and then depending on which breakpoint you’re on you either display:block;
or display:none;
. While it works that doesn’t seem like the most semantic way to approach the problem.
Instead I wanted to use the <abbr>
tag that came along with HTML5 so you would have <abbr title="Asia Pacific">APAC</abbr>
. That works perfectly for our small viewports, but what about when we want to show the larger version of the title? Well, that’s where CSS content can help us out. I add the class .responsive-abbr to the abbr element and then include the following in the CSS.
Here I’m checking if the viewport width is at least 35.5em and setting the font-size to 0 so the “APAC” is not seen. Then I’m setting a :before
pseudo element to set the font-size back to 1rem and then include the attr(title)
as the CSS content
. You can check this out on this code pen.
@media (min-width: 35.5em) {
.responsive-abbr {
font-size: 0;
}
.responsive-abbr:before {
font-size: 1rem;
content: attr(title);
}
}
See the Pen Responsive Abbreviations by Justin Avery (@justincavery) on CodePen.