CSS 中的伪类和伪元素有什么区别?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8069973/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is the difference between a pseudo-class and a pseudo-element in CSS?
提问by tybro0103
Things like a:link
or div::after
...
像a:link
或div::after
...
Information on the difference seems scarce.
关于差异的信息似乎很少。
回答by Zeta
The CSS 3 selector recommendationis pretty clear about both, but I'll try to show the differences anyway.
在CSS 3选择建议是关于双方很清楚,但我会尽量尝试显示的差异。
Pseudo-classes
伪类
Official description
官方说明
The pseudo-class concept is introduced to permit selection based on information that lies outside of the document tree or that cannot be expressed using the other simple selectors.
A pseudo-class always consists of a "colon" (
:
) followed by the name of the pseudo-class and optionally by a value between parentheses.Pseudo-classes are allowed in all sequences of simple selectors contained in a selector. Pseudo-classes are allowed anywhere in sequences of simple selectors, after the leading type selector or universal selector (possibly omitted). Pseudo-class names are case-insensitive. Some pseudo-classes are mutually exclusive, while others can be applied simultaneously to the same element. Pseudo-classes may be dynamic, in the sense that an element may acquire or lose a pseudo-class while a user interacts with the document.
引入伪类概念是为了允许基于位于文档树之外或无法使用其他简单选择器表达的信息进行选择。
伪类总是由一个“冒号” (
:
) 后跟伪类的名称和可选的括号之间的值组成。选择器中包含的所有简单选择器序列中都允许使用伪类。在前导类型选择器或通用选择器(可能省略)之后,在简单选择器序列中的任何位置都允许使用伪类。伪类名称不区分大小写。一些伪类是互斥的,而另一些伪类可以同时应用于同一个元素。伪类可能是动态的,因为当用户与文档交互时,元素可能会获得或丢失伪类。
What does this mean?
这是什么意思?
The important nature of pseudo-classes is stated in the very first sentence: "the pseudo-class concept [...] permit selection". It enables the author of an stylesheet to differ between elements based on information that "lies outside of the document tree", for example the current status of a link (:active
,:visited
). Those aren't saved anywhere in the DOM, and there exists no DOM interface to access these options.
伪类的重要性质在第一句话中说明:“伪类概念 [...]允许选择”。它使样式表的作者能够根据“位于文档树之外”的信息(例如链接 ( :active
, :visited
)的当前状态)在元素之间进行区分。这些不会保存在 DOM 中的任何地方,并且不存在访问这些选项的 DOM 接口。
On the other hand, :target
could be accessed via DOM manipulation (you could use window.location.hash
in order to find the object with JavaScript), but this "cannot be expressed using the other simple selectors".
另一方面,:target
可以通过 DOM 操作访问(您可以使用window.location.hash
JavaScript 查找对象),但这 “不能使用其他简单的选择器来表达”。
So basically a pseudo-class will refine the set of selected elements as any other simple selectorin a sequence of simple selectors. Note that all simple selectors in a sequence of simple selectors will be evaluated at the same time. For a complete list of pseudo-class check the CSS3 selector recommendation.
因此,基本上伪类将细化集合中选择元素作为任何其他的简单的选择器在一个简单的选择的序列。请注意,将同时评估一系列简单选择器中的所有简单选择器。如需伪类的完整列表,请查看 CSS3 选择器推荐。
Example
例子
The following example will color all even rows gray (#ccc
), all uneven rows which aren't dividable by 5 white and every other row magenta.
下面的示例将所有偶数行涂成灰色 ( #ccc
),所有不能被 5 个白色分割的不均匀行和每隔一行都涂成洋红色。
table tr:nth-child(2n) td{
background-color: #ccc;
}
table tr:nth-child(2n+1) td{
background-color: #fff;
}
table tr:nth-child(2n+1):nth-child(5n) td{
background-color: #f0f;
}
Pseudo-elements
伪元素
Official description
官方说明
Pseudo-elements create abstractions about the document tree beyond those specified by the document language. For instance, document languages do not offer mechanisms to access the first letter or first line of an element's content. Pseudo-elements allow authors to refer to this otherwise inaccessible information. Pseudo-elements may also provide authors a way to refer to content that does not exist in the source document (e.g., the
::before
and::after
pseudo-elements give access to generated content).A pseudo-element is made of two colons (
::
) followed by the name of the pseudo-element.This
::
notation is introduced by the current document in order to establish a discrimination between pseudo-classes and pseudo-elements. For compatibility with existing style sheets, user agents must also accept the previous one-colon notation for pseudo-elements introduced in CSS levels 1 and 2 (namely, :first-line, :first-letter, :before and :after). This compatibility is not allowed for the new pseudo-elements introduced in this specification.Only one pseudo-element may appear per selector, and if present it must appear after the sequence of simple selectors that represents the subjects of the selector.
Note: A future version of this specification may allow multiple pseudo-elements per selector.
伪元素创建了超出文档语言指定的文档树的抽象。例如,文档语言不提供访问元素内容的第一个字母或第一行的机制。伪元素允许作者参考这些否则无法访问的信息。伪元素还可以提供作者的方式来指代并不在源文档中存在的内容(例如,
::before
和::after
伪元素授予访问生成的内容)。伪元素由两个冒号 (
::
) 后跟伪元素的名称组成。
::
当前文档引入了这种表示法,以便在伪类和伪元素之间建立区分。为了与现有的样式表兼容,用户代理还必须接受之前在 CSS 级别 1 和 2 中引入的伪元素的单冒号表示法(即:第一行、:第一字母、:之前和:之后)。本规范中引入的新伪元素不允许这种兼容性。每个选择器只能出现一个伪元素,如果存在,它必须出现在代表选择器主题的简单选择器序列之后。
注意:本规范的未来版本可能允许每个选择器有多个伪元素。
What does this mean?
这是什么意思?
The most important part here is that "pseudo-elements allow authors to refer to [..] otherwise inaccessible information"and that they "may also provide authors a way to refer to content that does not exist in the source document (e.g., the ::before
and ::after
pseudo-elements give access to generated content).". The biggest difference is that they actually create a new virtual element on which rules and even pseudo-class selectors can be applied to. They don't filter elements, they basically filter content (::first-line
,::first-letter
) and wrap it in a virtual container, which the author can style however he want (well, almost).
这里最重要的部分是“伪元素允许作者引用 [..] 否则无法访问的信息”,并且它们“还可以为作者提供一种引用源文档中不存在的内容的方法(例如,::before
和::after
伪元素可以访问生成的内容)。”。最大的区别在于它们实际上创建了一个新的虚拟元素,规则甚至伪类选择器都可以应用于该元素。它们不过滤元素,它们基本上过滤内容 ( ::first-line
, ::first-letter
) 并将其包装在一个虚拟容器中,作者可以根据需要对其进行样式设置(好吧,几乎)。
For example the ::first-line
pseudo-element cannot be reconstructed with JavaScript, as it heavily depends on the current used font, the fonts size, the elements width, floating elements (and probably the time of the day). Well, that's not entirely true: one could still calculate all those values and extract the first line, however doing so is a very cumbersome activity.
例如,::first-line
伪元素不能用 JavaScript 重建,因为它在很大程度上取决于当前使用的字体、字体大小、元素宽度、浮动元素(可能还有一天中的时间)。嗯,这并不完全正确:人们仍然可以计算所有这些值并提取第一行,但是这样做是一项非常麻烦的活动。
I guess the biggest difference is that "only one pseudo-element may appear per selector". The note says that this could be subject to change, but as of 2012 I don't believe we see any different behavior in the future (it's still in CSS4).
我想最大的区别是“每个选择器只能出现一个伪元素”。该说明说这可能会发生变化,但截至 2012 年,我认为我们在未来不会看到任何不同的行为(它仍然在 CSS4 中)。
Example
例子
The following example will add a language-tag to every quote on a given page using the pseudo-class :lang
and the pseudo-element ::after
:
以下示例将使用伪类:lang
和伪元素为给定页面上的每个引号添加语言标签::after
:
q:lang(de)::after{
content: " (German) ";
}
q:lang(en)::after{
content: " (English) ";
}
q:lang(fr)::after{
content: " (French) ";
}
q:not(:lang(fr)):not(:lang(de)):not(:lang(en))::after{
content: " (Unrecognized language) ";
}
TL;DR
TL; 博士
Pseudo-classes act as simple selectors in a sequence of selectors and thereby classify elements on non-presentational characteristics, pseudo-elements create new virtual elements.
伪类充当一系列选择器中的简单选择器,从而对非表现特征进行分类,伪元素创建新的虚拟元素。
References
参考
W3C
W3C
- Selectors Level 3
- CSS 2.1 Specification(outdated but still informative)
- 5.2 Selector syntax:
A simple selector is either a type selector or universal selector followed immediately by zero or more attribute selectors, ID selectors, or pseudo-classes, in any order. The simple selector matches if all of its components match.
- 5.10 Pseudo-elements and pseudo-classes
- 5.2 Selector syntax:
- 选择器级别 3
- CSS 2.1 规范(过时但仍提供信息)
- 5.2 选择器语法:
一个简单的选择器是一个类型选择器或通用选择器,后面紧跟零个或多个属性选择器、ID 选择器或伪类,以任何顺序。如果它的所有组件都匹配,则简单选择器匹配。
- 5.10 伪元素和伪类
- 5.2 选择器语法:
回答by SLaks
A pseudo-class filters existing elements.a:link
means all <a>
s that are :link
.
伪类过滤现有元素。a:link
表示所有<a>
s :link
。
A pseudo-element is a new fake element.div::after
means non-existing elements after <div>
s.
伪元素是新的伪元素。div::after
表示<div>
s之后不存在的元素。
::selection
is another example of a pseudo-element.
It doesn't mean all elements that are selected; it means the range of content that is selected, which may span portions of multiple elements.
::selection
是伪元素的另一个例子。
这并不意味着所有元素都被选中;它表示选择的内容范围,它可能跨越多个元素的一部分。
回答by jerone
Short description that helped me to understand the difference:
帮助我理解差异的简短描述:
- Pseudo-classes describe a special state.
- Pseudo-elements match virtual elements.
- 伪类描述了一种特殊的状态。
- 伪元素匹配虚拟元素。
回答by motoxer4533
From the Sitepoint docs:
从 Sitepoint 文档:
A pseudo-classis similar to a class in HTML, but it's not specified explicitly in the markup. Some pseudo-classes are dynamic—they're applied as a result of user interaction with the document. - http://reference.sitepoint.com/css/pseudoclasses. These would be things like
:hover, :active, :visited
.Pseudo-elementsmatch virtual elements that don't exist explicitly in the document tree. Pseudo-elements can be dynamic, inasmuch as the virtual elements they represent can change, for example, when the width of the browser window is altered. They can also represent content that's generated by CSS rules. - http://reference.sitepoint.com/css/pseudoelements. These would be things like
before, :after, :first-letter
.
一个伪类是类似于HTML的一类,但它不是在标记明确指定。一些伪类是动态的——它们是作为用户与文档交互的结果而应用的。- http://reference.sitepoint.com/css/pseudoclasses。这些将是像
:hover, :active, :visited
.伪元素匹配文档树中不明确存在的虚拟元素。伪元素可以是动态的,因为它们代表的虚拟元素可以改变,例如,当浏览器窗口的宽度改变时。它们还可以表示由 CSS 规则生成的内容。- http://reference.sitepoint.com/css/pseudoelements。这些将是像
before, :after, :first-letter
.
回答by Sheo Dayal Singh
Below is the simple answer:
下面是简单的答案:
We use pseudo-classwhen we need to apply css based on the stateof an element. Such as:
当我们需要根据元素的状态应用 css 时,我们使用伪类。如:
- Apply css on hover of anchor element (
:hover
) - Apply css when gets focus on an html element (
:focus
). etc.
- 在锚元素 (
:hover
) 的悬停上应用 css - 当焦点在 html 元素上时应用 css (
:focus
)。等等。
We use pseudo-elementwhen we need to apply css to the specific partsof an elements or a newly inserted content. Such as:
当我们需要将 css 应用于元素的特定部分或新插入的内容时,我们使用伪元素。如:
- Apply the css to first letter or first line of an element (
::first-letter
) - Insert content before, or after, the content of an element (
::before
,::after
)
- 将 css 应用于元素的第一个字母或第一行 (
::first-letter
) - 在元素 (
::before
,::after
) 的内容之前或之后插入内容
Below is the example of both:
下面是两者的例子:
<html>
<head>
<style>
p::first-letter { /* pseudo-element */
color: #ff0000;
}
a:hover { /* pseudo-class */
color: red;
}
</style>
</head>
<body>
<a href="#" >This is a link</a>
<p>This is a paragraph.</p>
</body>
</html>
回答by Gerard ONeill
A conceptual answer:
概念性回答:
A pseudo-element refers to things that are part of the document, but you just don't know it yet. For example the first letter. Before you only had text. Now you have a first letter that you can target. It is a new concept, but was always part of the document. This also includes things like
::before
; while there isn't actual content there, the concept of something before something else was always there -- now you are specifying it.A pseudo-class is state of something in the DOM. Just like a class is a tag you associate with an element, a pseudo-class is a class that gets associated by the browser or DOM or whatever, usually as a response to a change in state. When a user visits a link -- that link can take on the state of 'visited'. You can imagine the browser applying the class 'visited' to the Anchor element.
:visited
would then be how you select for that pseudo-class.
伪元素指的是属于文档的一部分,但您只是还不知道它。例如第一个字母。在你只有文本之前。现在您有了可以定位的第一个字母。这是一个新概念,但始终是文档的一部分。这还包括诸如
::before
; 虽然那里没有实际内容,但始终存在先于其他事物的概念——现在您正在指定它。伪类是 DOM 中某物的状态。就像类是与元素关联的标签一样,伪类是由浏览器或 DOM 或其他任何东西关联的类,通常作为对状态变化的响应。当用户访问链接时——该链接可以呈现“已访问”状态。您可以想象浏览器将 'visited' 类应用到 Anchor 元素。
:visited
然后将是您为该伪类选择的方式。
回答by Sumant
Pseudo-Class
伪类
A pseudo-class is way of selecting certain parts of a HTML document, based in principle not on the HTML document tree itself and its elements or on characteristics like name, attributes or contents, but on other phantom conditions like language encoding or the dynamic state of an element.
伪类是选择 HTML 文档某些部分的方法,原则上不是基于 HTML 文档树本身及其元素或名称、属性或内容等特征,而是基于其他幻象条件,例如语言编码或动态状态的一个元素。
The original pseudo-class defined dynamic states of an element that are entered and exited over time, or through user intervention. CSS2 expanded on this concept to include virtual conceptual document components or inferred portions of the document tree e.g. first-child. Pseudo-classes operate as if phantom classes were added to various elements.
原始伪类定义了元素的动态状态,随着时间的推移或通过用户干预进入和退出。CSS2 扩展了这个概念以包括虚拟概念文档组件或文档树的推断部分,例如第一个孩子。伪类的操作就像将幻像类添加到各种元素一样。
RESTRICTIONS: Unlike pseudo-elements, pseudo-classes can appear anywhere in selector chain.
限制:与伪元素不同,伪类可以出现在选择器链中的任何位置。
Example pseudo-class code:
示例伪类代码:
a:link /* This selects any "a" element whose target has not been visited.*/
{
padding : 4px;
text-decoration : none;
width : 10%;
color : #000000; /* black text color */
background-color : #99FF99; /* set to a pastel green */
border-top : 2px solid #ccffcc; /* highlight color */
border-left : 2px solid #ccffcc; /* highlight color */
border-bottom : 2px solid #003300; /* shadow color */
border-right : 2px solid #003300; /* shadow color */
}
a:visited /* This selects any "a" element whose target has been visited.*/
{ padding : 4px;
text-decoration : none;
color : #000000; /* black text color */
background-color : #ccccff; /* set to a lavender */
border-top : 2px solid #ffffff; /* highlight color */
border-left : 2px solid #ffffff; /* highlight color */
border-bottom : 2px solid #333366; /* shadow color *
border-right : 2px solid #333366; /* shadow color */
}
a:hover /* This selects any "a" element which is in a hover state. This is a state during pointer movement within the rendering region of an element. The user designates an element but does not activate it. */
{
color : #000000; /* black text color */
background-color : #99cc99; /* desaturated color */
border-top : 2px solid #003300; /* shadow color */
border-left : 2px solid #003300; /* shadow color */
border-bottom : 2px solid #ccffcc; /* highlight color */
border-right : 2px solid #ccffcc; /* highlight color */
}
a:focus /* This selects any "a" element which currently has focus. Focus is a state during which an element accepts keyboard input or other forms of text input. */
{
padding : 4px;
text-decoration : none;
width : 10%;
color : #000000; /* black text color */
background-color : #ffff99; /* set to a pastel yellow */
border-top : 2px solid #ffffcc; /* highlight color */
border-left : 2px solid #ffffcc; /* highlight color */
border-bottom : 2px solid #666633; /* shadow color */
border-right : 2px solid #666633; /* shadow color */
}
a:active /* This selects any "a" element which is in a state of activation. Active is a state during pointer activation (eg: press and release of a mouse) within the rendering region of an element.*/
{
padding : 4px;
text-decoration : none;
width : 10%;
color : #000000; /* black text color */
background-color : #ff99ff; /* set to a pink */
border-top : 2px solid #ffccff; /* highlight color */
border-left : 2px solid #ffccff; /* highlight color */
border-bottom : 2px solid #663366; /* shadow color */
border-right : 2px solid #663366; /* shadow color */
}
A page that demonstrates a rendering of the above pseudo-class code
演示上述伪类代码渲染的页面
Pseudo-elements
伪元素
PSEUDO-ELEMENTS are used to address sub-parts of elements. They allow you to set style on a part of an element's content beyond what is specified in the documents. In other words they allow logical elements to be defined which are not actually in the document element tree. Logical elements allow implied semantic structure to be addressed in CSS selectors.
伪元素用于处理元素的子部分。它们允许您在文档中指定的元素内容之外设置样式。换句话说,它们允许定义实际上不在文档元素树中的逻辑元素。逻辑元素允许在 CSS 选择器中处理隐含的语义结构。
RESTRICTIONS: Pseudo-elements may only be applied to external and document-level contexts - not to in-line styles. Pseudo-elements are restricted in where they can appear in a rule. They may only appear at the end of a selector chain (after the subject of the selector). They should come after any class or ID names found in the selector. Only one pseudo-element can be specified per selector. To address multiple pseudo-elements on a single element structure, multiple style selector/declaration statements must be made.
限制:伪元素只能应用于外部和文档级上下文 - 不适用于内嵌样式。伪元素被限制在它们可以出现在规则中的位置。它们可能只出现在选择器链的末尾(在选择器的主题之后)。它们应该出现在选择器中找到的任何类或 ID 名称之后。每个选择器只能指定一个伪元素。要处理单个元素结构上的多个伪元素,必须进行多个样式选择器/声明语句。
Pseudo-elements can be used for common typographic effects such as initial caps and drop caps. They can also address generated content that is not in the source document (with the "before" and "after") An example style sheet of some pseudo-elements with properties and values added follows.
伪元素可用于常见的排版效果,例如首字母大写和首字下沉。它们还可以处理不在源文档中的生成内容(带有“之前”和“之后”) 下面是一些添加了属性和值的伪元素的示例样式表。
/* The following rule selects the first letter of a heading 1 and sets the font to 2em, cursive, with a green background. First-letter selects the first rendered letter/character for a block-level element. */
/* 以下规则选择标题 1 的第一个字母,并将字体设置为 2em,草书,背景为绿色。First-letter 为块级元素选择第一个呈现的字母/字符。*/
h1:first-letter {
font-size : 2em;
font-family : "Lucida Handwriting", "Lucida Sans", "Lucida Console", cursive;
background-color : #ccffcc;
}
/* The following rule selects the first displayed line in a paragraph and makes it bold. First-line selects the first rendered line on the output device of a block-level element. */
p:first-line {
font-weight : bold;
}
/* The following rule selects any content placed before a blockquote and inserts the phrase "Quote of the day:" in bold small caps with a green background. */
blockquote:before {
content : "Quote of the day:";
background-color : #ccffcc;
font-weight : bold;
font-variant : small-caps;
}
/* The following rule selects any content placed before a "q" element and inserts the smart open quote. */
q:before {
content : open-quote;
}
/* The following rule selects any content placed after a "q" element and inserts the smart close quote. */
q:after{
content : close-quote;
}
Sources:Link
资料来源:链接
回答by DavidRR
In brief, from Pseudo-classeson MDN:
简而言之,来自MDN 上的伪类:
A CSS pseudo-classis a keyword added to a selector that specifies a special state of the selected element(s). For example,
:hover
can be used to apply a style when the user hovers over a button.div:hover { background-color: #F89B4D; }
CSS伪类是添加到选择器的关键字,用于指定所选元素的特殊状态。例如,
:hover
可用于在用户将鼠标悬停在按钮上时应用样式。div:hover { background-color: #F89B4D; }
And, from Pseudo-elementson MDN:
并且,来自MDN 上的伪元素:
A CSS pseudo-elementis a keyword added to a selector that lets you style a specific part of the selected element(s). For example,
::first-line
can be used to style the first line of a paragraph./* The first line of every <p> element. */ p::first-line { color: blue; text-transform: uppercase; }
CSS伪元素是添加到选择器的关键字,可让您设置所选元素的特定部分的样式。例如,
::first-line
可用于设置段落第一行的样式。/* The first line of every <p> element. */ p::first-line { color: blue; text-transform: uppercase; }