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

前端之家收集整理的这篇文章主要介绍了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:'';
}
原文链接:https://www.f2er.com/css/216560.html

猜你在找的CSS相关文章