2

I have the task to display an abbreviation on small screen and the full term on a large screen (e.g. "CSS" on small, "Cascading Style Sheets" on big screens).

I can easily do it by outputting both terms, each with a class and display:none one of them depending on media queries.

I was asking myself if I can use the abbr element to do it in a better way using this markup:

<abbr title="Cascading Style Sheets">CSS</abbr>

Below you can see how for I've got with the attr() CSS property and that it's not rendering properly. My problem is that the abbr would somehow needed to be stretched out to fit in the long term. Is there a way to do this with CSS?

@media (min-width: 500px) {
  abbr {
    display: inline-block;
    text-indent: -9999px;
  }
  abbr::before {
    content: attr(title);
    position: absolute;
    text-indent: 9999px;
  }
}
<p>
    I'm using 
    <abbr title="Cascasing Style Sheets"> CSS </abbr> 
    for responsive text changes.
</p>

https://codepen.io/smichaelsen/pen/VwYeZQZ

smichaelsen
  • 158
  • 8
  • There is already https://stackoverflow.com/questions/7896402/how-can-i-replace-text-with-css though I don't think solutions there would work for you, maybe [a font-size hack](https://jsfiddle.net/4thxc5mn/) could be acceptable, and I'm pretty sure there is another Q/A with such an hack. – Kaiido Dec 10 '19 at 09:01

1 Answers1

3

The simplest way to do this would be to put an span inside the abbr so that you have something you can select with the CSS to hide. That would look something like this:

@media (min-width: 500px) {
  abbr {
    text-decoration: none;
  }
  abbr span {
    display: none;
  }
  abbr::before {
    content: attr(title);
  }
}
<p>
  I'm using
  <abbr title="Cascasing Style Sheets"> <span>CSS<span> </abbr> for responsive text changes.
</p>

Alternatively, you could set the font-size of abbr to 0. This has the advantage of not needing any extra spans but it does mean you have to explicitly set the font-size of abbr::before. This seems like it's more likely to cause headaches down the line but it does work pretty cleanly.

For this I also added a blank space to the end of the content since setting the font-size to 0 effective removes the space after the ::before.

@media (min-width: 500px) {
  abbr {
    font-size: 0;
    text-decoration: none;
  }
  abbr::before {
    content: attr(title) " ";
    font-size: 16px;
  }
}
<p>
  I'm using
  <abbr title="Cascasing Style Sheets"> CSS </abbr> for responsive text changes.
</p>

Side note: I added text-decoration: none; to both examples since once you've expanded the abbr you don't really want it to look like an abbreviation.

cjc
  • 731
  • 3
  • 13