我的任务是在小屏幕上显示缩写,在大屏幕上显示完整术语(例如,在小屏幕上显示“ CSS”,在大屏幕上显示“级联样式表”)。
我可以通过输出两个术语来轻松做到这一点,每个术语都有一个类,而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
内,以便您可以使用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>
或者,可以将
font-size
的abbr
设置为0。这具有不需要任何额外的span
的优点,但这确实意味着您必须显式设置font-size
的abbr::before
。这似乎更容易引起麻烦,但是确实可以正常工作。为此,我还在
content
的末尾添加了一个空格,因为将font-size
设置为0会删除::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>
旁注:我已经在两个示例中都添加了
text-decoration: none;
,因为一旦您扩展了缩写,您实际上并不想让它看起来像缩写。