何时使用 :before 或 :after

When to use :before or :after

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

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

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

请允许我演示一下:

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

请不要告诉我这只是个人喜好问题。哈哈

DEMO

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

一旦使用

position: absolute;

在伪元素(完全合法)中,伪元素的名称是 ::before 还是 ::after.

不再重要

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