基础:
在伪类 :before
、:after
中的使用 content
属性来为 HTML 局部添加内容现在已经成了很常见的做法,特别是一些 icon 的显示,非常好用,最基本的使用如下:
<style>
div:after {
content: "text from 'content' property";
}
</style>
<div></div>
但今天看到一篇文章 知道了其实 content
属性中其实还可以直接获取元素的 attribute 属性:
div:after {
content: attr(text);
}
</style>
<div text="text from 'text' attribute"></div>
demo:
See the Pen dataset in CSS by Lien (@movii) on CodePen.
标题中获取 dataset,这里首先得明确一下,其实直接获取元素的 attribute 也是可以的。而为什么尽量使用 dataset 下文中会提到。
在上面例子中直接使用的 text="text from 'text' attribute"
,原文中不太推荐这么做,因为这是一个 attribute:
attr is typically used with custom data- attributes since traditional element attributes are good for functionality but not so much or text presentation.
不做直接翻译,大概理解为:HTML 标签里的 attribute 是功能性的,比如 <select>
里的 required
或者 <option>
上可以加入的 selected
,虽然可以使用,但不推荐,因为在这里只是一段 text 数据,属于 data 的范畴,按照语义化更应该使用 data-text
在这里写入数据。所以上面的例子可以写成这样:
div:after {
content: attr(data-text);
}
</style>
<div data-text="text from 'text' attribute"></div>
另一个结合 :after
和 :hover
的例子:
See the Pen dataset in CSS 2 by Lien (@movii) on CodePen.
concatenate attr()
with text:
还有另外一种用法也是上文中提到的 blog 文章中介绍的,将获取到的 data-text
与别的内容合并:
<style>
div:after {
content: "content + " attr(data-text);
}
</style>
<div data-text="text from 'text' attribute"></div>
See the Pen dataset in CSS 2 by Lien (@movii) on CodePen.
技术发展迭代很快,所以这些笔记内容也有类似新闻的时效性,不免有过时、或者错误的地方,欢迎指正 ^_^。
BEST
Lien(A.K.A 胡椒)