The CSS content
property is primarily used with the ::before
and ::after
pseudo-elements to insert generated content into an element. This can include text, images, or symbols that aren’t part of the document’s main content.
Syntax
selector::before { content: value; } selector::after { content: value; }
Values
none
: Default value; no content is inserted.normal
: Inserts normal content, which can depend on the context (e.g., a counter value).string
: Inserts the specified text.url()
: Inserts an image specified by a URL.attr()
: Inserts the value of an attribute of the selected element.open-quote
/close-quote
: Inserts the appropriate quotation marks.counter()
: Inserts the value of a counter.inherit
: Inherits thecontent
property from its parent element.
Example Usage
- Inserting Text
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>CSS Content Example</title> <style> p::before { content: "Note: "; font-weight: bold; color: red; } </style> </head> <body> <p>This is a paragraph with a prefix added using the ::before pseudo-element.</p> </body> </html>
Output: The paragraph will start with “Note:” in bold and red, followed by the original text.
- Adding a Symbol
<style> p::after { content: " ✓"; color: green; } </style>
Adds a green checkmark after the paragraph text.
- Using
attr()
to Display an Attribute<style> a::after { content: " (" attr(href) ")"; color: gray; } </style>
This will display the URL in parentheses after each link.
- Inserting an Image
<style> div::before { content: url('icon.png'); margin-right: 10px; } </style>
This will insert an image (icon.png) before the content of a
<div>
.
Practical Example
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>CSS Content Property Example</title> <style> h1::before { content: "🌟 "; } h1::after { content: " 🌟"; } p::after { content: " Read more..."; color: blue; cursor: pointer; } </style> </head> <body> <h1>CSS Content Property</h1> <p>This paragraph will have additional content appended to it.</p> </body> </html>
Output:
- The
<h1>
will be wrapped with star emojis. - The
<p>
will have “Read more…” appended in blue, indicating it might be clickable.
Use Cases
- Decorative purposes: Add icons, symbols, or additional text to elements.
- Content labeling: Prefix or suffix content with contextual information.
- Dynamic content: Display attribute values or counters dynamically.
Best Practices
- Use the
content
property for styling purposes and not for adding essential content, as it is not accessible to screen readers and does not contribute to the document’s semantics. - Ensure any dynamically added content does not affect the usability or accessibility of the page.