Previous Section  < Day Day Up >  Next Section

Recipe 8.3 Inserting URLs After Links

Problem

You need to display URLs of links in an article when a web page is printed.

Solution

Instruct the browser to print the URLs of links in a paragraph by using the :after pseudo-element:

p a:after {

 content: " <" attr(href) "> " ;

}

Discussion

Selector constructs such as :after are known as pseudo-elements. The browser interprets the selector as though additional elements were used to mark up the web document.

For example, by using the following CSS, you can make the first letter of a paragraph two-em units in size:

p:first-letter {

 font-size: 2em;

}

You use the :after selector (or the :before selector) to insert generated content after (or before) an element. In this Recipe, the value of the href attribute, which contains the URL information, is placed after every anchor element in a p element.

To have brackets appear around the URL, place the quotes around the brackets. To add a buffer of space between the anchor element and the next inline content, put one space in front of the left bracket and one after the right bracket, then insert the URL using the attr(x) function. Whatever attribute is replaced for x, CSS finds the attribute in the element, returning its value as a string.

Another example of the power of this pseudo-element involves returning the value of abbreviations and acronyms in a buzzword-laden document. To accomplish this, first put the expanded form of the word or phrase in the title attribute for abbr or acronym:

<p>The <acronym title="World Wide Web Consortium">W3C</a> 

makes  wonderful things like <abbr title="Cascading Style 

Sheets">CSS</abbr>!</p>

Then, in the CSS rules, tell the browser to return the value for the title attribute:

abbr:after, acronym:after {

 content: " (" attr(title) ") ";   

}

Currently, generating content through pseudo-elements works only in Netscape 6+, Mozilla, and Safari browsers.

See Also

Recipe 1.2 for more on setting type in a web document; the CSS 2.1 specification about generated content at http://www.w3.org/TR/REC-CSS2/generate.html#content.

    Previous Section  < Day Day Up >  Next Section