「这是我参与11月更文挑战的第14天,活动详情查看:2021最后一次更文挑战」
“伪元素”,顾名思义。它创建了一个虚假的元素,并插入到目标元素内容之前或之后。
浏览器支持:before 和 :after 伪元素栈
很多人喜欢只写一个冒号,但是我当时看到规范说的是最好使用两个冒号,当然一个冒号也是生效的
下面可以看到这个内容前后插入了伪元素
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
#test {
width: 100px;
height: 100px;
background: aqua;
}
#test::after{
content: '?'
}
#test::before{
content: '!'
}
</style>
</head>
<body>
<div id='test'></div>
</body>
</html>
伪元素如果没有设置“content”属性,伪元素是无用的。
插入的内容在页面的源码里是不可见的。只能在css里可见,所以,不要使用伪元素生成内容,是您的网页的可用性和可访问性的关键。
插入的元素在默认情况下是内联元素(或者,在html5中,在文本语义的类别里)。因此,为了给插入的元素赋予高度,填充,边距等等,你通常必须显式地定义它是一个块级元素。
伪元素不会继承
你可以包含一个指向一个图像的URL,就像在css里包含一个背景图像一样,content的url不能使用引号引住,不然会认为使用一个字符串
#test::before{
content: url(./4.png)
}
在一次错误使用伪元素的时候,去了解了一下官方的解释。就是我用img的时候,想使用伪元素,发现怎么都效果,可以看到下面官方的解释。所以大家还是不要在img标签上去使用伪元素的好
As their names indicate, the :before and :after pseudo-elements specify the location of content before and after an element's document tree content.The 'content' property, in conjunction with these pseudo-elements, specifies what is inserted.
顾名思义,:before 和:after 伪元素指定元素的文档树内容之前和之后的内容位置。 'content' 属性与这些伪元素一起指定插入的内容。
Note. This specification does not fully define the interaction of :before and :after with replaced elements (such as IMG in HTML). This will be defined in more detail in a future specification. 本规范没有完全定义 :before 和 :after 与替换元素(例如 HTML 中的 IMG)的交互。这将在未来的规范中更详细地定义。