CSS Before and After Pseudo-Elements (Part 1): Getting Started

Most likely along the line somewhere, you must have come across ::before (or :before) and ::after (or :after) in some CSS codes and have been asking what they are and what exactly they are used for. Those you see there are referred to as pseudo-elements. As the name pseudo implies, they’re anonymous as they are used to apply styles to sections in web pages without actually defining any new HTML element. Today I will be showing you how they can be applied to style web pages and the implications of using them (::before and ::after).

Please note that either the single colon (:) or double (::) colon can be used to implement the before and after pseudo-elements, but the double colon is what is used in CSS3. It was introduced to distinguish the pseudo-elements from the pseudo-classes.

Before (::before)

As the name implies, the ::before element is used to create and style an anonymous element before the main content of the element we’re actually dealing with. A lot of people have a misconception that pseudo-elements are created outside of the element it is applied to like the image below shows.

But it actually isn’t so. The pseudo-elements are created within the element we’re dealing with as shown below.

NOTE: To implement a visible pseudo-element, it must take in one very important property: content. If this property is not defined all the applied styles will not be visible.

Example:

Using the ::before pseudo-element to insert an opening quotation mark.

HTML
CSS
RESULT

After (::after)

This is the same as the before pseudo-element, but this time the anonymous element is created after the element being dealt with – not out of the element, but still within the element.

Example:

Using the ::after pseudo-element to insert a closing quotation mark.

CSS
RESULT

In my next article I’ll be showing you how to make a tool tip without JavaScript using just the ::before or ::after pseudo-elements.

2
0

Related Posts