DEV Community

What Are :before and :after Pseudo Elements?

Nesha Zoric on May 22, 2018

The CSS :before and :after properties are what also known as pseudo elements. They are used to add something before or after the content of an elem...
Collapse
 
maxart2501 profile image
Massimo Artizzu • Edited

Unless you're targeting IE8 without Autoprefixer or similar processor, please use the syntax with two colons: ::before and ::after.
The single colon syntax is for pseudo classes, while the double colon is for pseudo elements.

Anyway, another nice use? Triangles!

h2::before {
  content: "";
  border-style: solid;
  border-width: 10px 10px 10px 0;
  border-color: transparent currentcolor;
}

Triangles are just some basic shape, you can actually have some fun with them. And it's still a legit use as they're still decorations.

Collapse
 
patrickcole profile image
Patrick Cole

Thanks for pointing this out Massimo! I guess I had not picked up on the fact that the double colon was the updated spec for pseudo elements. Definitely helped me understand the difference between the pseudo elements and pseudo classes!

Collapse
 
neshaz profile image
Nesha Zoric

Hey, Massimo! Yes, I agree, triangles are very interesting. This article was focused on the basic usage of :before and :after element, but triangles are indeed a great example. Thanks! :)

Collapse
 
maxfontana90 profile image
maxfontana90

I think it's worth to mention that this could bring accesibility issues to your webpage. Imagine you have a class like the following:

.required::after {
content: "*";
}

that is intended to be used in form inputs to highlight those that are mandatory. The approach would prevent accesible guests to be aware of which fields are required, since the * symbol has a contextual meaning.

Collapse
 
neshaz profile image
Nesha Zoric

Thanks for mentioning it! Because of accessibility issues, the usage of these pseudo elements should definitely be well planned.

Collapse
 
gsonderby profile image
Gert Sønderby

I've recently used :before and :after pseudo-elements on nested unordered lists and their items to create a tree view. Works really well!

Collapse
 
millebi profile image
Bill Miller

Note: For those with accessibility concerns the :before and :after are regularly not "properly" processed for screen readers, etc...