Type to generate custom UI components with AI

Type to generate UI components from text

OR

Browse thousands of MUI, Tailwind, React components that are fully customizable and responsive.

Explore Components

Use CSS Content Property to Dynamically Make Great Content

Would you like to dynamically generate content on your web page using CSS content property? The content property in CSS lets you generate content before or after an HTML element renders on your web page.

This CSS feature is used with pseudo-elements and lets you insert generated content such as text and images.

In this tutorial, we’ll explain how the CSS content property works and how you can use it to dynamically add content and style your template.

Understanding CSS Content Property

The content property is a fundamental aspect of CSS that allows developers to insert generated content into their HTML. This property is primarily used with pseudo-elements (::before and ::after) to add content before or after the actual content of an element.

Understanding how the content property works and its diverse applications is crucial for developers aiming to enhance the presentation of their web pages.

To learn more about how pseudo elements work in CSS, check out the video below.

Importance of Using the CSS Content Property

The CSS content property plays a crucial role in web development, offering a versatile way to enhance the presentation and styling of HTML elements. Here are some of the benefits of using the content property:

1. Dynamic Content Insertion

The content property allows developers to dynamically insert content into the HTML document. This is particularly useful for scenarios where the content needs to be generated dynamically or pulled from external data sources.

2. Styling Pseudo-elements

Pseudo-elements, such as ::before and ::after, are commonly used to insert elements using the content property. This allows you to add decorative elements, labels, or additional information to elements without modifying the actual HTML markup.

3. Enhancing Accessibility

With the content property thoughtfully, you can enhance the accessibility of a website. For example, adding labels or accessible text to elements provides additional context for users who rely on screen readers.

4. Automatic Numbering and Counters

The content property, in conjunction with counters, enables the automatic numbering of elements. This is especially valuable when styling ordered lists or other sequentially organized content.

5. Decorative Styling

For purely presentational purposes, the content property allows you to add decorative elements, icons, or separators to enhance the visual appeal of the webpage.

6. Responsive Design

The content property can be employed to create responsive designs, adapting content based on different screen sizes or device characteristics.

Speaking of responsive design, if you’d like to cut down on development time, we suggest checking out PureCode. PureCode uses AI to generate responsive and customizable components to style your web project.

Access PureCode’s CSS Templates

Basic Usage of CSS Content

The CSS content property is used to insert content generated by CSS into HTML elements. It is commonly applied to pseudo-elements, such as ::before and ::after. Allowing you to add content before or after the actual content of an element without modifying the HTML structure.

Here’s an example illustrating how the content property is used to insert content before and after an element:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <style>
    /* CSS styling */
    .custom-content::before {
      content: "Before Text: ";
      font-weight: bold;
      color: blue;
    }

    .custom-content::after {
      content: " After Text.";
      font-style: italic;
      color: green;
    }
  </style>
  <title>CSS Content Property Example</title>
</head>
<body>
  <!-- HTML content with CSS-generated content -->
  <div class="custom-content">
    This is the main content.
  </div>
</body>
</html>

In this example:

  • The .custom-content::before selector applies styles and inserts the content “Before Text: ” before the actual content of the element.

  • The .custom-content::after selector applies styles and inserts the content ” After Text.” after the actual content of the element.

When you view this HTML page in a browser, the rendered content will appear as:

The pseudo-class requires the content property. You can add a string value to it or use it to add an image or quotation mark to your HTML. Let’s explore some of examples.

1. Inserting Images:

You can use the url() function within the content property to insert an image. Make sure to set appropriate dimensions and styles to control the appearance.

.image-content::before {
  content: url('path/to/your-image.jpg');
  width: 50px;
  height: 50px;
  display: inline-block; /* Ensures inline alignment */
}

2. Inserting Icons:

You can also include icon fonts or SVGs using the content property to insert them. The following example uses Font Awesome for icons in the content property:

.icon-content::before {
  content: "f007"; /* Unicode character for the Font Awesome icon */
  font-family: 'Font Awesome 5 Free';
  font-weight: 900; /* Adjust as needed for the specific icon */
  color: #3498db;
}

Note: You’ll need to make sure you have the Font Awesome CSS included in your HTML for this to work.

3. Inserting Quotes:

You can use the open-quote and close-quote values within the content property to insert quotation marks into your HTML template. This is often used for styling blockquotes.

.quote-content::before {
  content: open-quote;
  font-size: 1.5em; /* Adjust size as needed */
  color: #555;
}

.quote-content::after {
  content: close-quote;
  font-size: 1.5em;
  color: #555;
}

The close-quote value only works with the ::after pseudo-element and will not produce anything if a value of open-quote is not also present on the same element using ::before.

The no-open-quote value removes the opening quote from the specified element and the no-close-quote removes the closing quote. This can be particularly useful if you have multiple quotes property nested within each other in your HTML markup.

If you’d like to hide some of the quotes nested on your page, you can use the no-open-quote and no-close-quote property to implement it.

Putting it all together:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="path/to/fontawesome/css/all.min.css"> <!-- Include Font Awesome CSS -->
  <style>
    .image-content::before {
      content: url('path/to/your-image.jpg');
      width: 50px;
      height: 50px;
      display: inline-block;
    }

    .icon-content::before {
      content: "f007";
      font-family: 'Font Awesome 5 Free';
      font-weight: 900;
      color: #3498db;
    }

    .quote-content::before {
      content: open-quote;
      font-size: 1.5em;
      color: #555;
    }

    .quote-content::after {
      content: close-quote;
      font-size: 1.5em;
      color: #555;
    }
  </style>
  <title>CSS Content Property Examples</title>
</head>
<body>
  <p class="image-content">This is a paragraph with an image before it.</p>

  <p class="icon-content">This is a paragraph with a Font Awesome icon before it.</p>

  <blockquote class="quote-content">
    This is a blockquote with quotes styled using the CSS content property.
  </blockquote>
</body>
</html>

These examples showcase how the content property can be utilized to enhance the visual presentation of HTML content by dynamically inserting images, icons, and quotes through CSS.

Advanced Techniques with CSS Content

The content property in CSS offers advanced techniques beyond simple text or decorative additions. Two notable features are the attr() function and the counter & counters functions.

Using the attr() Function for Dynamic Content

The attr() function allows you to insert the value of an HTML attribute as content. This is particularly useful for dynamic content or when you want to reflect the value of an attribute in your styles.

[data-label]::before {
  content: attr(data-label);
  font-weight: bold;
  color: #3498db;
}

In this example, the content before an element is dynamically set based on the value of the “data-label” attribute. This is beneficial when you want to insert information that may change dynamically, such as labels or captions.

Using Counter and Counters

CSS provides the counter and counters functions, which allow you to create and increment counters. These counters can be used to generate automatic numbering for content.

ol {
  counter-reset: section; /* Initialize the counter */
}

li::before {
  content: counter(section) ". "; /* Insert the counter value before each list item */
  counter-increment: section; /* Increment the counter */
}

In this example, an ordered list (ol) is styled to automatically number each list item using the counter function. The counter-reset property initializes the counter. You can use any value for the counter reset property. However, when using the value in the pseudo element, you’ll need to use the same name you specified as the counter-reset property.

Here is the complete HTML code for the examples we covered below.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <style>
    /* Using the attr() function for Dynamic Content */
    [data-label]::before {
      content: attr(data-label);
      font-weight: bold;
      color: #3498db;
    }

    /* Using Counter and Counters */
    ol {
      counter-reset: section;
      list-style: none;
      padding: 0;
    }

    li::before {
      content: counter(section) ". ";
      counter-increment: section;
      margin-right: 0.5em;
    }
  </style>
  <title>Advanced CSS Content Techniques</title>
</head>
<body>
  <p data-label="Dynamic Label">This paragraph has a dynamic label.</p>

  <ol>
    <li>Item 1</li>
    <li>Item 2</li>
    <li>Item 3</li>
  </ol>
</body>
</html>

In this complete example:

  • The ::before pseudo-element is used with the attr() function to dynamically insert content based on the “data-label” attribute.

  • The ol and li elements demonstrate the use of counter and counter-reset to automatically number list items.

These advanced techniques with the content property provide powerful ways to generate dynamic and automatic content in your styles.

CSS Content Property and Responsive Design

The CSS content property can be used in responsive design to adapt and customize content based on different screen sizes. Here’s a breakdown of how the content property contributes to responsive design:

1. Media Queries

Media queries enable developers to apply styles based on specific conditions, such as screen width or device type. The content property can be employed within media queries to dynamically insert content for different viewports.

@media (max-width: 600px) {
  .responsive-content::before {
    content: "Mobile View: ";
  }
}

@media (min-width: 601px) and (max-width: 1024px) {
  .responsive-content::before {
    content: "Tablet View: ";
  }
}

@media (min-width: 1025px) {
  .responsive-content::before {
    content: "Desktop View: ";
  }
}

In this example, the content property is used within media queries to display different messages based on the width of the viewport. This ensures that users on various devices receive content tailored to their screen size.

2. Adapting Content Placement

The content property can also be used to dynamically adjust the placement or style of content for responsive layouts. For instance, you might want to add labels or icons to certain elements only on larger screens.

@media (min-width: 768px) {
  .responsive-icon::before {
    content: url('icon-large.png');
  }
}

@media (max-width: 767px) {
  .responsive-icon::before {
    content: url('icon-small.png');
  }
}

Here, the content property is used to dynamically insert different icons based on the screen width. This approach enhances the design by adapting the content based on the available space.

3. Conditional Content Display:

The content property can conditionally display or hide content based on the viewport size. This is particularly useful for showing or hiding specific information on smaller screens.

@media (max-width: 480px) {
  .responsive-message::before {
    content: "Tap to expand";
  }
}

@media (min-width: 481px) {
  .responsive-message::before {
    content: "Hover for details";
  }
}

In this example, the content property is used to change the message displayed before an element based on whether the screen is narrow or wide.

Best Practices for Using CSS Content

  1. Screen Reader Testing: Test your content with screen readers to ensure that inserted content is read aloud correctly.

  2. Contrast and Readability: Ensure sufficient contrast between the inserted content and the background for readability.

  3. Responsive Design: If using the content property for responsive design, ensure that the inserted content adapts well to different screen sizes.

  4. Avoid Information Overload: Don’t overload the page with inserted content. Keep it concise and relevant.

  5. Use ARIA Roles if Necessary: If the inserted content represents interactive or dynamic elements, consider using ARIA roles to enhance accessibility.

Semantic Use of the Content Property

The semantic use of the CSS content property refers to employing this property in a way that preserves the meaning and structure of the HTML document.

When used semantically, the inserted content should contribute to the understanding and context of the document rather than serving purely presentational or decorative purposes.

Benefits of Semantic Use:

  1. Accessibility: Semantic use of the content property ensures that inserted content is meaningful and contributes positively to the overall user experience, especially for users relying on assistive technologies.

  2. Maintaining Structure: Semantic content preserves the logical structure of the document, making it easier for developers and other stakeholders to understand and maintain the codebase.

  3. Search Engine Optimization (SEO): When used to enhance the meaning of content, the content property can contribute to improved SEO by providing search engines with more context about the page.

Common Hitches and How to Avoid Them

The CSS content property is a versatile tool, but it comes with its own set of challenges. Understanding these common issues and implementing effective strategies can help ensure smooth development and styling. Here’s a detailed explanation of these challenges and how to avoid them:

1. Not Adding Space or Separators

Without a space or separator in the content property, generated content may concatenate with the actual content, leading to unexpected visual results.

Solution: Always include a space or appropriate separator within the content property to maintain proper formatting.

.article::before {
  content: "Latest Article: ";
}

2. Quotation Marks and Escaping

Unescaped quotation marks within the content property can cause unexpected behavior, especially when dealing with strings.

Solution: Escape quotes or use a combination of single and double quotes to prevent parsing issues.

.quote::before {
  content: "Quoted text 'Another quote within a quote'";
}

3. Empty Content

Setting the content property to an empty string may result in unexpected rendering or no visible content.

Solution: Ensure there is meaningful content or use a default value to prevent unintentional rendering issues.

.empty-content::before {
  content: "No content available";
}

4. Dynamic Content Challenges

The attr() function may not work as expected in certain situations, especially when dealing with dynamic content.

Solution: Verify browser compatibility and, if necessary, use JavaScript to handle dynamic content insertion.

[data-label]::before {
  content: attr(data-label);
}

5. Limited Support for Counters

Limited browser support or potential conflicts with certain CSS properties when using counters.

Solution: Check browser compatibility and use fallbacks or alternative approaches for numbering elements.

ol {
  counter-reset: section;
}

li::before {
  content: counter(section) ". ";
  counter-increment: section;
}

6. Overusing content Property

Overusing the content property may lead to complex and less maintainable styles, making it challenging to debug and modify.

Solution: Consolidate styles where possible, consider using actual HTML content for more complex scenarios, and prioritize readability and maintainability.

.overuse::before {
  content: "Note: ";
}

.overuse::after {
  content: " End of note.";
}

Regular testing, understanding browser compatibility, and maintaining clean and organized styles contribute to a more seamless development experience.

Frequently Asked Questions

Below, we’ve answered some of the top questions about using the content property in CSS.

What is the CSS content property used for?

The CSS content property is used to insert generated content, often applied to pseudo-elements. It provides a way to enhance the presentation of web pages without modifying the HTML structure.

How can I insert text with line breaks using the content property?

To insert text with line breaks, use the A escape sequence within the content property. Here is an example:

.example::before {
  content: "First line A Second line";
  white-space: pre;
}

Is the content property applicable to all HTML elements?

The content property is primarily used with pseudo-elements (::before and ::after) and is not applicable to all HTML elements.

Can I use the content property to insert HTML elements?

The content property is designed for inserting text and cannot be used to insert HTML elements directly. However, dynamic content insertion with attr() can reflect HTML attribute values.

How does the content property impact SEO?

The content property, when used appropriately, does not impact SEO negatively. However, it is crucial to ensure that inserted content aligns with accessibility standards and does not compromise the overall user experience.

Adding Content Dynamically With CSS

The content property in CSS is a useful feature for applying complex styles to your HTML template without changing your HTML markup.

In this tutorial, we explained how the CSS content property works and its implementation using the ::before and ::after pseudo-elements. We also covered some advanced concepts like adding HTML attributes and using counter sets to customize list numbering.

If you’d like to speed up your development time, check out PureCode’s templates gallery. We have over 10,000 responsive templates for projects built using CSS3, Tailwind CSS, and Material UI.

Get Started with PureCode today

Further Reading

If this post was helpful to you, consider checking out the following related content to help you become a better developer.

David Ozokoye

David Ozokoye

Software Engineer and Technical Writer