Learn CSS, part 7: Pseudo Elements - The Content Property
(Page 5 of 6 )
The reason for including this section in this article is that the next two pseudo elements are dependent on this property. The content property is used in CSS to dynamically insert text from the CSS file into the Web page. This text is what we call generated content. This can be better explained with an example. Copy the following CSS code and save it as test.css:
div
{
content: "This is a Generated Content from the CSS file";
color: white;
background-color: black;
font-family: Tahoma;
font-size: 1.1em;
}
Now save the following HTML code to a file:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<link rel="stylesheet" href="test.css" type="text/css">
<title>CSS Pseudo Elements</title>
</head>
<body>
<div></div>
</body>
</html>
You need to open this page with Opera 7 in order to get the result, because it implements the content property in the way the CSS 3 Specifications state. Actually, in CSS 3 Specifications the content property can be used without the ::before and ::after pseudo elements, but in CSS 2 the specifications state that it must be used with ::before and ::after. Mozilla supports the content property as specified in CSS 2, so it must be used with the pseudo elements ::before and ::after.

Let's take it step by step. In the CSS file we have the div element selector, which applies the following rules to all of the div elements in the document. First, it will insert the character string data "This is a Generated Content from the CSS file" into all the <div> elements in the document. Second, it will set the text color to white and the background color to black. Finally, it will change the font-family to Tahoma and the size to 1.1em.
What's happening is that the browser inserts into the <div> elements the string value of the content property. Note that if there is some text inside the <div> element, it will be replaced with the string of the content's property value as in the following example. I just added another <div> element with some text inside and reloaded the Web page. As you can see, this text is never loaded; it's replaced with the string of the content's property value.
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<link rel="stylesheet" href="test.css" type="text/css">
<title>CSS Pseudo Elements</title>
</head>
<body>
<div></div>
<div>This is the div element's text</div>
</body>
</html>
Next: The ::before and ::after Pseudo Elements >>
More Style Sheets Articles
More By Michael Youssef