CSS allows you to add content to the beginning and end of an HTML element using the
::after pseudo-elements. These results are only visual and not actually in the DOM, meaning you can't add specific event handlers to them like you can regular DOM elements.
These pseudo-elements can be helpful in many cases. Real-world examples I've used them in include adding tails to comment bubbles and creating nice custom gradient effects for borders around an element.
In this blog, I use a
::before pseudo-element to add the i icon in a circle around all of my
blockquote elements to signify an important notice or alert about certain features.
Here is an example of a
blockquotetag I use to create the i icon in a circle, signifying something important to remember. This uses the
::beforepseudo-element in CSS for custom placement and styling.
Here is a simple code snippet illustrating the uses of the
From a layout point of view, this is it would be displayed:
<!-- other code inside the div element -->
In order for the contents to appear on screen, it's required to add a
content CSS rule to your pseudo-element. Omitting this rule will leave the contents blank.
Here are a few different values you can use:
- A string:
content: "a string";- Alpha-numeric characters. Special characters will need to be encoded as a unicode entity using glyphs.
- An image:
content: url("/path/to/image.jpg");- Adding a URL method with a path to the image file. Images as pseudo-elements cannot be resized, however you can set a
background-imagerule with custom image sizing, if needed.
content: "";- As mentioned, this is perfect in cases where you'd like to resize an image. You could also use this for custom styling where no text or images will be present.
There are no real differences between the two pseudo-elements as they render content inside their parent elements. The best way to think of it is how they would be displayed positionally. For example, if your pseudo-element content is positioned near the top or left of its parent element, use
::before. If the content will be positioned near the right or bottom, then use
Single vs. Double Quotes
While single quotes work perfectly fine, the double-quote version is standard practice when defining pseudo-elements like
::after. Otherwise, you're defining pseudo-classes like
The double quote version is the newer, standard format intended to distinguish between the two as of CSS3. And, if you don't need IE 8 support, then it's best to stick to best practices.
Pseudo-elements have been around for quite some time and are supported in all major browsers.
::after pseudo-elements are a great solution for adding content to your pages without the use of additional HTML code.
Created: August 22, 2022