Detailed explanation of CSS properties-the difference between pseudo-classes and pseudo-elements

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 w3cdefinition 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 cssthings can not be described.

Pseudo-class

Please enter a picture description

Types of pseudo-elements

Please enter a picture description

the difference

Here pseudo classes :first-childand pseudo elements :first-letterto be compared.

p>i:first-child {color: red}
<p>
    <i>first</i>
    <i>second</i>
</p>

Please enter a picture description// pseudo-classes :first-childto 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>

Please enter a picture description// pseudo-elements :first-letteradd 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 spanincrease 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 css3to 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.

Guess you like

Origin www.cnblogs.com/baimeishaoxia/p/12682424.html