什么是:: before或:: after表达式,为什么它显示在浏览器开发人员工具中?

lec*_*ine 3 html css pseudo-element

我读过::before用于在你使用它的元素之前添加内容,例如

p::before { 
    content: "Read this: ";
}
Run Code Online (Sandbox Code Playgroud)

但是我见过的大部分时间(通过开发人员工具窥视网页)他们使用它们没有任何元素,例如

<div class="btn-toolbar" role="toolbar">
      ::before
      <div class="btn-group">
        <button type="button" class="btn btn-default"><span class="glyphicon glyphicon-align-left"></span></button>
        <button type="button" class="btn btn-default"><span class="glyphicon glyphicon-align-center"></span></button>
        <button type="button" class="btn btn-default"><span class="glyphicon glyphicon-align-right"></span></button>
        <button type="button" class="btn btn-default"><span class="glyphicon glyphicon-align-justify"></span></button>
      </div>
      ::after
    </div>
Run Code Online (Sandbox Code Playgroud)

令人惊讶的是,当您查看网页源代码时,这些::before::after元素不会显示.

为什么它们显示在开发人员工具中?

Moh*_*deh 5

CSS-技巧:

CSS有一个名为content的属性.它只能与伪元素一起使用:after和:before.它被写成伪选择器(带冒号),但它被称为伪元素,因为它实际上并没有选择页面上存在的任何内容,而是向页面添加新内容.

::在使用css的元素之前插入内容之前.

q::before { 
  content: "«";
  color: blue;
}
Run Code Online (Sandbox Code Playgroud)

::在元素之后插入内容之后.

q::after { 
  content: "»";
  color: red;
}
Run Code Online (Sandbox Code Playgroud)

演示

你也可以使用特殊字符,其中一些:

\ 2018 - 左单智能报价

\ 2019 - 右单智能报价

\ 00A9 - 版权所有

\ 2713 - 复选标记

\ 2192-右箭头

\ 2190-左箭头

你也可以使用元素属性:

<a title="A web design community." href="http://css-tricks.com">CSS-Tricks</a>

a:before {
   content: attr(title) ": ";
}
Run Code Online (Sandbox Code Playgroud)

在这里阅读完整文章

  • 不完全正确:`:: before`在元素的*实际内容*之前(在其第一个子节点之前,但仍在元素本身内)插入内容(带图像的文本或文本,但不是HTML标记),类似于` :: after`,它在元素的实际内容之后插入内容(但仍在其中). (5认同)
  • 更新的答案仍然没有正确解释`:: before` /`:: after`伪元素的行为.引用的短语也是无关紧要的.问题是它们为何在开发人员工具中显示但未在HTML源代码中显示.这是因为 - 显然 - 你不能通过CSS修改文档的内容.实际上,伪元素被添加到DOM中,而不是HTML源. (3认同)