Difference between pseudo-class (colon :) and pseudo-element (double colon :: ) in CSS

Asked

Viewed 1,431 times

13

I would like to know the differences between these two concepts of CSS in order to understand and point out what one is, and what may be the other.

For example: :hover, ::before.

What I’ve understood so far is that - :: is pseudo-element and : is pseudo-class, correct?

1 answer

17


Pseudo-classes are used to select elements that cannot be expressed otherwise than using attributes such as: id's, classes (or any other type of information available through the DOM). For example: :first-child, :last-child, :lang() and :not().

table tr:first-child td {
   background-color: #ccc;
}
table tr:nth-child(2n) td {
   background-color: #fff;
}
:not(table) {
    color: #ff0000;
}

Pseudo-elements are "imaginary" elements (or virtual elements if you prefer) in which we can apply styles relatively as part of other real elements, but these imaginary elements are not part of the GIFT. For example, fragments of content such as ::first-line and ::first-letter or content virtually generated as - ::before and ::after.

p::first-letter {color: green;}
p::before { 
    content: "Leia isto: ";
}
p::after {
    content: url('../imagens/icon.png');
}

The sign :: was entered in the current document in order to establish a difference between pseudo-classes and pseudo-elements. The user Agents should also accept the sign of only two points : for compatibility with existing style sheets and pseudo-elements introduced in CSS 1 and 2 (i.e.: :first-line, :first-letter, :before and :after). This compatibility is not allowed for new pseudo-elements introduced in this. source

Sources and references: source, pseudo-classes, pseudo-Elements, selectors.

  • So in case the right one would be I update the pseudo-elements :before and :after for ::before and ::after?

  • 2

    Not necessarily @Viníciuslima . Although it is already seen to happen automatically when a pseudo element is created in certain browsers like Firefox, this update on its part is not an action that necessarily needs to be done because browsers must accept this compatibility as stated in blockquote of my answer. But yes, this is the correct way to mention pseudo elements. To mention pseudo elements with :: will only be sensitive to new pseudo elements that have been recently added or are to come in the future.

  • 1

    Concluding - You can start writing ::before from now on that is the correct form, but avoids running your style sheet altogether to make these updates because the two ways to write are acceptable. This will now only depend on your style of writing code that will vary from person to person.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.