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

标签 css css-selectors pseudo-element

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

伪类:

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.

例子:

  • :活跃
  • :检查
  • :第n个 child ()
  • :首先
  • :悬停

伪元素::

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.

例子:

  • ::之后
  • ::之前
  • ::第一个字母
  • ::一线
  • ::选择
  • ::背景

如@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.

关于css - 伪类和伪元素有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41867664/

相关文章:

javascript - 如果子元素包含字符串,如何删除容器

css - 重复的花园语法

javascript - 使用 Interactive.js/shadowDOM 选择器可拖动 polymer

html - 使用 CSS 定位所有跟随 h2 的 p 元素

伪元素后的 HTML 未按预期显示

html - 为什么此文本在我的移动设备上显得如此小?

html - 每个按钮上带有自定义图像或图标的 CSS 菜单

CSS :last-child:not(:only-child) not working as expected

jquery - 检测点击单选按钮+标签 :before

html - 如何在 HTML 链接标签中添加::after