问题
Before moving to my question, I know how the :before
and :after
selectors work. (not a duplicate of what is ::before or ::after expression). My question is in regards to use.
I've seen some inconsistencies over the years where these selectors have been used to display the same thing. Same results, different approach. In some specific cases, such as adding a font awesome icon within an li
before the a
the :before
selector makes sense. I'm not inquiring about that use, since it's intuitive enough to understand. But take a speech bubble for a tooltip for instance. I have seen the triangle placed with a :before
and also with an :after
and in some occasions they use both! I'm confused.
What is the determining factor on choosing which selector should be used to attach an element such as the triangle on a speech bubble?
Allow me to demonstrate:
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
Please don't tell me it's just a matter of preference. lol
DEMO
回答1:
The naming of ::before
and ::after
is not entirely arbitrary, but it only really makes sense when the content of those pseudo elements is displayed inline, just before or just after the content of the element they are attached to.
As soon as you use
position: absolute;
in a pseudo element (which is totally legitimate), it no longer matters whether that pseudo element is named ::before
or ::after
.
It might just as easily be named ::presentational-frill-1
or ::presentational-frill-2
.
来源:https://stackoverflow.com/questions/34827794/when-to-use-before-or-after