Perhaps the easiest way to get a sense of how pseudo-elements work is to see one in action:
In the demo above, try replacing the exclamation points in the
content property with something different. Where does the new content appear? Can you change the selector to make the content appear after the text?
In the example above, we use the pseudo-element
:before selector on the element to which we wish to prepend the content. Then, whatever we put between the quotes in the value for the
content property is shown before the paragraph. The additional CSS properties in the selector block are applied to the inserted content, resulting in larger blue exclamation points here.
It's important to know that content added using pseudo-elements is not actually added to the document; it is only there visually, just as a background image isn't added to the content of the page. This means the content isn't readable by search engines or screen-readers.
It's important to remember that pseudo-element content is not readable by screen-readers or other assistive technology.
Because of these considerations, and to maintain the separation of concerns between HTML and CSS, you should never use pseudo-elements for anything other than decorative, non-essential content.
Styling Inserted Content
As demonstrated, whatever CSS is written within the
:after selector block is applied to the content inserted by the
content property. The possibilities are virtually limitless.
For instance, we may want to set the inserted content to behave as a block element instead of the default inline behavior. All we need do is use the
display property, just as we would on any other element:
In the above demo, can you change the color of the smiley face? Can you center align it?
Because the inserted content acts as a child of the element to which it is attached, it is possible to position the inserted content as an absolutely relative to the canvas of the parent. (For a refresher on this technique, refer to Absolute Child with a Relative Parent from the chapter on the
All we have to do is set the element to which the inserted content is attached to
position: relative and the
:after selector to
position: absolute. Then we can use the
top properties to the values we desire.
In the demo above, can you move the heart to the upper right of the card? What happens if you remove
position: relative from the div?