CSS-Generated Content

As we've learned, HTML is for content and CSS is for style. But sometimes, we want to add cosmetic, style-only content for visual purposes. For this we can use the :before and :after pseudo-elements in CSS, in combination with the content property, to insert content before or after an element.


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 :before or :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?

Absolute Positioning

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 position property.)

All we have to do is set the element to which the inserted content is attached to position: relative and the :before or :after selector to position: absolute. Then we can use the bottom, left, right, and/or 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?