通过 CSS 使用 abbr 元素进行响应式文本更改

Using the abbr element for responsive text change with CSS

我的任务是在小屏幕上显示缩写,在大屏幕上显示完整术语(例如 "CSS" 在小屏幕上,"Cascading Style Sheets" 在大屏幕上)。

我可以通过输出两个术语来轻松做到这一点,每个术语都有一个 class 和 display:none 其中之一,具体取决于媒体查询。

我问自己是否可以使用 abbr 元素以使用此标记以更好的方式完成它:

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

下面您可以看到我如何使用 attr() CSS 属性 并且它没有正确呈现。我的问题是 abbr 需要以某种方式延长以适应长期需求。有没有办法用 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

最简单的方法是在 abbr 中放置一个跨度,这样您就可以 select 使用 CSS 隐藏一些东西。看起来像这样:

@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>

或者,您可以将 abbrfont-size 设置为 0。这样做的优点是不需要任何额外的 span,但这确实意味着您必须显式设置font-sizeabbr::before。这似乎更容易引起头痛,但它确实非常干净。

为此,我还在 content 的末尾添加了一个空白 space,因为将 font-size 设置为 0 有效地删除了 [=22] 之后的 space =].

@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>

旁注:我在两个示例中都添加了 text-decoration: none;,因为一旦你扩展了缩写,你就不会真的希望它看起来像一个缩写。