HTML and CSS Reference
In-Depth Information
Generating Content with CSS
You can generate page content using the following
before
and
after
pseudo-elements
along with the
content
property
selector
:before {content:
text
;}
selector
:after {content:
text
;}
where
text
is the text you want to add to the element. For example, the style rule
em:after {content: “ !”;}
appends a space and an exclamation point to the end of every
em
element. You also can
use the
before
and
after
pseudo-elements in conjunction with pseudo-classes. The
style rules
a:hover:before {content: “<”;}
a:hover:after {content: “>”;}
create a rollover effect in which the
<
and
>
characters are placed around a hypertext
link when a mouse pointer hovers over the link.
Another way to insert content using CSS is to retrieve information from an element
attribute using the
attr
property, which has the syntax
content: attr(
attribute
)
where
attribute
is an attribute of the element. For example, the following style
appends every hypertext link with the text of the link's URL as stored in the
href
attribute:
a:after {
content: attr(“ [“ attr(href) “] “);
}
When applied to the hypertext link
<a href=”home.htm”>Sunny Acres</a>
this style will be rendered by the browser as follows:
Sunny Acres [home.htm]
Finally, you can insert an image by specifying the URL of the image file for the value
of the
content
property, as the following code demonstrates:
a[href^=”http”]:after {
content: url(uparrow.png);
}
In this example, the
uparrow.png
file is appended to any hypertext link that contains
the text string
http
within its
href
attribute. This technique is sometimes used to visually
identify hypertext links that point to external Web sites.
By generating content through your CSS style sheets, you can create interesting
dynamic effects for your Web site that are easy to develop and maintain. Note, however,
that the
content
pseudo-class is not supported in older browsers, and so you should not
rely on it to create text critical to the understanding of your Web site.