css – 为什么:before和:after伪元素需要一个’content’属性?

给定以下情况,为什么:after选择器需要content属性才能运行?
.test {
    width: 20px;
    height: 20px;
    background: blue;
    position:relative;
}
			
.test:after {
    width: 20px;
    height: 20px;
    background: red;
    display: block;
    position: absolute;
    top: 0px;
    left: 20px;
}
<div class="test"></div>

请注意,在指定content属性之前,您如何看不到伪元素:

.test {
    width: 20px;
    height: 20px;
    background: blue;
    position:relative;
}
			
.test:after {
    width: 20px;
    height: 20px;
    background: red;
    display: block;
    position: absolute;
    top: 0px;
    left: 20px;
    content:"hi";
}
<div class="test"></div>

为什么这是预期的功能?你会认为显示块会强制元素出现.奇怪的是,你可以看到Web调试器中的样式;但是,它们不显示页面上.

解决方法

以下是对各种W3C规范和草案的一些参考:

Selectors Level 3

The ‘:before’ and ‘:after’ pseudo-elements can be used to insert generated content before or after an element’s content.

The :before and :after pseudo-elements

Authors specify the style and location of generated content with the :before and :after pseudo-elements. 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.

The content attribute

Initial: none

This property is used with the :before and :after pseudo-elements to generate content in a document. Values have the following meanings:

noneThe pseudo-element is not generated.

应用于:: before和:: after伪元素的样式会影响生成内容显示.内容属性是这个生成内容,如果没有,内容认值为none,这意味着没有什么可以应用于样式.

如果你不想重复内容:”;多次,您可以通过CSS中的伪元素(JSFiddle example)之间的所有:: before和::全局样式来覆盖:

::before,::after {
    content:'';
}

相关文章

Css3如何实现鼠标移上变长特效?(图文+视频)
css3怎么实现鼠标悬停图片时缓慢变大效果?(图文+视频)
jquery如何实现点击网页回到顶部效果?(图文+视频)
css3边框阴影效果怎么做?(图文+视频)
css怎么实现圆角边框和圆形效果?(图文+视频教程)
Css3如何实现旋转移动动画特效