为什么伪元素需要一个“content”属性? [英] Why do pseudo-elements require a 'content' property?

查看:711
本文介绍了为什么伪元素需要一个“content”属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

鉴于以下情况,为什么:after selector需要一个content属性才能运行?

Given the following scenario, why does the :after selector require a content property to function?

<div class="test"></div>

.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属性之前,如何看到伪元素。

Notice how you do not see the pseudo element until you specify the content property.

为什么这是预期的功能?你会认为显示块会强制元素出现。奇怪的是,你可以看到web调试器中的样式;

Why is this the intended functionality? You would think that the display block would force the element to show up. Oddly enough, you can actually see the styles inside web debuggers; however, they do not display on the page.

推荐答案

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

Here are some references to various W3C specifications and drafts:


':before'和':after'伪元素可用于在元素内容之前或之后插入生成的内容。

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



:before和:after伪元素



The :before and :after pseudo-elements


作者使用:before和:after伪元素指定生成内容的样式和位置。如他们的名字所示,:before和:after伪元素指定元素的文档树内容之前和之后的内容的位置。 content属性与这些伪元素一起指定要插入的内容。



< a href =http://www.w3.org/TR/CSS2/generate.html#propdef-content>内容属性



The content attribute


初始:

Initial: none

此属性与:before和:after - 要在文档中生成内容的元素。值具有以下含义:

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

- 不生成伪元素。 b $ b

none - The pseudo-element is not generated.






应用于:: before和:: after伪元素的样式会影响生成内容的显示。 content 属性此生成的内容,如果不存在,默认值为 content:none 假设,这意味着样式不能应用于任何内容。


The styling applied to ::before and ::after pseudo-elements affects the display of the generated content. The content attribute is this generated content, and without it present, the default value of content: none is assumed, meaning there is nothing for the style to be applied to.

如果您不想重复 content: '; 多次,你可以覆盖这个简单的全局样式的所有:: before和:: after伪元素在CSS( JSFiddle example ):

If you don't want to repeat content:''; multiple times, you can override this simply by globally styling all ::before and ::after pseudo-elements within your CSS (JSFiddle example):

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

这篇关于为什么伪元素需要一个“content”属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆