css - 何时使用 :before or :after

标签 css pseudo-element

在回答我的问题之前,我知道 :before:after 选择器是如何工作的。 (不是 what is ::before or ::after expression 的副本)。我的问题是关于使用。

这些年来,我看到了一些不一致的地方,这些选择器被用来显示相同​​的东西。同样的结果,不同的方法。在某些特定情况下,例如在 a 之前的 li 中添加 Font Awesome 图标 :before 选择器是有意义的。我不是在询问这种用法,因为它足够直观,可以理解。但以工具提示的对话泡泡为例。我见过用 :before:after 放置的三 Angular 形,在某些情况下它们同时使用!我很困惑。

选择使用哪个选择器附加元素(例如对话泡泡上的三 Angular 形)的决定因素是什么?

请允许我演示:

HTML

<div class="container">
    <div class="bubble">This is my text in a bubble using :after</div>
    <div class="bubble2">This is my text in a bubble using :before</div>
</div>

CSS

.bubble{
  position: relative;
  padding: 15px;
  margin: 1em 0 3em;
  color: #000;
  background: #f3961c;
  border-radius: 10px;
  background: linear-gradient(top, #f9d835, #f3961c);
}

.bubble:after {
  content: "";
  display: block; 
  position: absolute;
  bottom: -15px;
  left: 50px;
  width: 0;
  border-width: 15px 15px 0;
  border-style: solid;
  border-color: #f3961c transparent;
}


.bubble2 {
  position: relative;
  padding: 15px;
  margin: 1em 0 3em;
  color: #000;
  background: #f3961c;
  border-radius: 10px;
  background: linear-gradient(top, #f9d835, #f3961c);
}

.bubble2:before {
  content: "";
  display: block; 
  position: absolute;
  bottom: -15px;
  left: 50px;
  width: 0;
  border-width: 15px 15px 0;
  border-style: solid;
  border-color: #f3961c transparent;
}

IMG

enter image description here

请不要告诉我这只是一个偏好问题。哈哈

DEMO

最佳答案

::before::after 的命名并不是完全随意的,但只有在显示那些伪元素的内容时才真正有意义 内联,就在它们附加到的元素的内容之前或之后。

一旦你使用

position: absolute;

在一个伪元素(这是完全合法的)中,该伪元素是命名为 ::before 还是 ::after 不再重要。

它可能很容易命名为 ::presentational-frill-1::presentational-frill-2

关于css - 何时使用 :before or :after,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34827794/

相关文章:

html - 将元素符号图标更改为双引号

CSS继承: Override an ID parent selector with a CLASS child

调整按钮大小时,chrome 上的 CSS 在 firefox 上表现不同

html - 管理移动网站和主网站的CMS

html - div 元素中的数据属性并显示在::after 伪元素上

html - 为什么开发人员在父 div 上使用::before 伪元素和 display:table

css - float div 之间的水平线

CSS 底部边距问题

javascript - FullPage JS固定背景不工作

CSS flexbox 包装 FireFox 中的内容(不是 Chrome)