Article:Understanding the CSS ‘content’ Property

Extarct from the SitePoint Article “Understanding the CSS ‘content’ Property” by Gajendar Singh

If you are a front-end developer there is a good chance that you have heard about pseudo-elements as well as CSS’s content property. I won’t discuss pseudo-elements in depth here, but I suggest you take a look at this Louis Lazaris’ article on Smashing Magazine if you are unfamiliar with the concept or need a quick refresher.

In this article, we’ll focus on the content property. CSS’s content property works with the ::before and ::after pseudo-elements (which can use either single- or double-colon synax). The property is used to insert generated content in a web page and it is fully supported in all major browsers.

Basic Syntax for the content Property

p::before {
  content: normal|counter|attr|string|open-quote|url|initial|inherit;
}

The CSS differs slightly from value to value. For example, to use the attr() value with ::before or ::after, you need to write CSS like the following:

p::after {
  content: " (" attr(title) ")";
}

That’s just one example, and more on that later. In the following sections I will discuss each value, including attr().

Value: none or normal

When set to none, the pseudo-element is not generated. If you set it to normal it computes to none for the ::before and ::after pseudo-elements.

p::before {
  content: normal;
}
 
p::after {
  content: none;
}

This kind of thing might be used in nested elements that already have a pseudo-element defined but you want to override the pseudo-element in certain contexts.

Value: <string>

This value sets the content to a string and can be any text content. If using non-latin characters, the characters need to be encoded. Let’s look at examples of each. Consider the following HTML:

<h2>Tutorial Categories</h2>
  <ol>
    <li>HTML and CSS</li>
    <li class="new">Sass &amp; Less</li>
    <li>JavaScript</li>
  </ol>
 
<p class="copyright">SitePoint, 2015<p>

And then the following CSS:

.new::after {
  content: " New!";
  color: green;
}
 
.copyright::before {
  content: "\00a9  ";
}

Here we are inserting text content into one of the list items, and also inserting an encoded character (in this case, the copyright symbol) into the paragraph element.

Continue reading this article on SitePoint …

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.