伪类和伪元素有什么区别?

What is the difference between pseudo-classes and pseudo-elements?

div::after {}div:after {} 和有什么不一样?我们什么时候必须使用 :: 而不是 :

Double colon and single-colon notation is to distinguish between pseudo-classes and pseudo-elements.

以上语句的实际含义是什么?

来自https://developer.mozilla.org/en-US/docs/Learn/CSS/Introduction_to_CSS/Pseudo-classes_and_pseudo-elements

Pseudo-class :

A CSS pseudo-class is a keyword, preceded by a colon (:), added to the end of selectors to specify you want to style the selected elements, and only when they are in certain state. For example, you might want to style an element only when it is being hovered over by the mouse pointer, or a checkbox when it is disabled or checked, or an element that is the first child of its parent in the DOM tree.

示例:

  • :活跃
  • :选中
  • :nth-child()
  • :第一个
  • :悬停

Pseudo-elements::

Pseudo-elements are very much like pseudo-classes, but they have differences. They are keywords, this time preceded by two colons (::), that can be added to the end of selectors to select a certain part of an element.

示例:

  • ::之后
  • ::之前
  • ::first-letter
  • ::first-line
  • ::选择
  • ::背景

如@stephanmg 所述:

In practice ::before is used as :before and ::after is used as :after because of browser compatibility. Both are pseudo-elements, but may look like pseudo classes. This might be confusing if you read CSS code.

Pseudo-classes : 它由浏览器自动应用 取决于元素的位置或其交互状态。

例如:

E:hover 光标在时匹配E类型的元素 悬停在上面。

Pseudo-elements : 将样式应用于内容 基于其在 HTML 层次结构中的位置。

例如:

E::first-letter 这将样式应用于 block-level 中第一行的第一个字母 元素E.

所以,

CSS3 选择器规范前缀 pseudo-elements 有两个冒号而不是一个。 所以,:first–letter 变成了 ::first-letter 而 :first-line 变成了 ::first-line。 IE 8 及更早版本不理解 double-colon 前缀,因此您需要使用 single-colon 版本以避免在旧浏览器中破坏样式。