CSS `content` Property: Generating Dynamic Content for Pseudo-elements

Learn how to use the CSS `content` property to dynamically generate text and other content for `:before` and `:after` pseudo-elements. This tutorial explains various `content` property values, demonstrating techniques for adding decorative elements, counters, and other dynamic text to enhance your web designs.



Generating Content with CSS `content` Property

Understanding the `content` Property

The CSS `content` property allows you to dynamically generate content for pseudo-elements (`:before` and `:after`). This is a powerful tool for adding decorative elements, counters, or other dynamic text to your HTML elements. It's important to note that the `content` property only works with pseudo-elements; you cannot use it to directly change the content of an element itself.

`content` Property Syntax and Values

The syntax is:

content: normal | none | counter | string | attr() | open-quote | close-quote | no-close-quote | no-open-quote | url() | initial | inherit;

Here's a breakdown of the values:

Value Description
normal (Default) The browser determines the content.
none No content is generated.
counter Generates a counter value (often a number). Uses the `counter()` or `counters()` functions.
string Generates a specific text string (must be enclosed in quotes).
attr(attributeName) Generates the value of an HTML attribute. Returns an empty string if the attribute doesn't exist.
open-quote Inserts an opening quotation mark.
close-quote Inserts a closing quotation mark.
no-open-quote Suppresses the automatic insertion of an opening quotation mark.
no-close-quote Suppresses the automatic insertion of a closing quotation mark.
url(url) Embeds a media resource (image, audio, video).
initial Sets the property to its default value.
inherit Inherits the value from the parent element.

Examples of `content` Property Usage

The following examples illustrate the `content` property with different values. Each example uses the `::before` pseudo-element to add content *before* an element; you can similarly use `::after` to add content *after* an element.

Using `normal` and `none`

This shows how to use `content: normal;` (browser default) and `content: none;` to control whether content is generated before a paragraph.

Using `string` and `url()`

This illustrates adding text using `content: string;` and embedding an image using `content: url();`.

Using `open-quote` and `close-quote`

This shows how to add quotation marks. Note that `close-quote` requires `open-quote`.

Using `no-open-quote` and `no-close-quote`

This example demonstrates suppressing the automatic addition of quotation marks.

Using `attr()`

This example demonstrates using `attr()` to display the value of an HTML attribute.