I wrote a blog post "Detailed CSS Properties-: before &&: after" before . At that time, I didn't distinguish between pseudo-elements and pseudo-classes, so I confused the concept in the article. Fortunately, @riophae brother corrected my mistake, so Today I plan to study the difference between the two.
First, read the w3c
definition of the two:
-
CSS
Pseudo-classes are used to add special effects to certain selectors. -
CSS
Pseudo-elements are used to add special effects to certain selectors.
Two points can be made clear. The first two are related to the selector, and the second is to add some "special" effects. Special here refers to both describe other css
things can not be described.
Pseudo-class
Types of pseudo-elements
the difference
Here pseudo classes :first-child
and pseudo elements :first-letter
to be compared.
p>i:first-child {color: red}
<p>
<i>first</i>
<i>second</i>
</p>
// pseudo-classes :first-child
to add style to the first child
if we do not use pseudo-classes, and hope to achieve these results, you can do this:
.first-child {color: red}
<p>
<i class="first-child">first</i>
<i>second</i>
</p>
That is, we add a class to the first child element, and then define the style of this class. Then we next look at the elements:
p:first-letter {color: red}
<p>I am stephen lee.</p>
// pseudo-elements :first-letter
add style to the first letter
So if we do not use pseudo-elements to achieve these results, it should be how to do it?
.first-letter {color: red}
<p><span class='first-letter'>I</span> am stephen lee.</p>
That is, we add a letter to the first span
, and then to span
increase styles.
The difference between the two has come out. That is:
The effect of pseudo-classes can be achieved by adding an actual class, and the effect of pseudo-elements can be achieved by adding an actual element, which is why they are called pseudo-classes and pseudo-elements.
to sum up
Pseudo-elements and pseudo-classes reason so confusing, because of their similar effect and the wording is similar, but in fact css3
to distinguish between the two, a pseudo-class has been defined by a colon to indicate, while pseudo-elements are used with two colons Said.
:Pseudo-classes
::Pseudo-elements
But because of compatibility issues, most of them are still unified single colons, but aside from compatibility issues, we should develop good habits as much as possible when writing, to distinguish between the two.