微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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.jb51.cc/css/216560.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。