This is the first in a series of “today I learned” posts. Today it’s all about the pseudo element ::before
and ::after
. This isn’t new news to most I’m sure, but I’ve just recently started using these and think they are pretty cool.
Say you are working on a site where you have access to the styles but not the DOM. You need to add an element to the page without actually adding any markup to a page. That’s where ::before
and ::after
come in. You can add either of these .element::before
or .element::after
to add extra element to the DOM this way.
I created an example (albeit kinda crude) to show how to use the elements. The snowman’s torso is a DOM element and the head and foot are added via .snowman::before
and .snowman::after
css elements. Same with the hands, there’s a empty .hand
element on the page and the left and right hands are placed with .hands::before
and .hands::after
.
See the Pen MKVwLg by Nate Nolting (@natenolting) on CodePen.0
One caveat I’ve found is if you want the added ::before
or ::after
to behave like a block element you must add content: "";
to your css in order for the element to display, otherwise it has no height or width.
It does seem that we can all use it, so go a make some pseudo elements!