XML technologies / CSS / CSS Cookbook / Printing / Displaying the URI after a link

(Excerpt from “CSS Kochbuch” by Christopher Schmitt)

Problem

When the page is printed, display the corresponding URIs (Uniform Resource Identifiers) after links.

Solution

Use the pseudo-element :after to tell the browser to output the URIs of links in a paragraph:

p a:after {
 content: " <" attr(href) "> " ;
}

Discussion

Selectors such as :after are called pseudo-elements. The browser interprets the selector as if the web document contained an additional element.

For example, the following CSS gives the first letter of a paragraph a size of two ems:

p:first-letter {
 font-size: 2em;
}

The selector :after (or the related selector :before) lets you insert automatically generated content after or before an element. This recipe inserts the value of the attribute href, containing the URI to display, after each element a within a paragraph.

The angle brackets displayed around the URI must be enclosed in quotation marks in the CSS rule. To separate the URI visually from the remaining content, a space is added before and after the angle brackets. Between them is the function attr(x), which reads the value of the attribute href. This value is then included as a string in the generated content.

Another example of this pseudo-element’s versatility is displaying the expanded words of acronyms in a document full of buzzwords. The full term must be in the attribute title of an element abbr or acronym:

<p>Das <acronym title="World Wide Web Consortium">W3C</a> erfindet wunderbare Dinge wie zum Beispiel <abbr title="Cascading Style Sheets">CSS</abbr>!</p>

Then use a CSS rule to tell the browser to output the value of the attribute title:

abbr:after, acronym:after {
 content: " (" attr(title) ") ";
}

Displaying the domain name before root-relative links

For root-relative links, printing displays only the slash and the directory and file names that follow it. The substring selector from the CSS 3 specification can work around this problem:

p a:after {
 content: " <" attr(href) "> " ;
}
p a[href^="/"]:after {
 content: " <http://www.csscookbook.com" attr(href) "> " ;
}

The caret (^) tells the selector to match only links beginning with a slash. This distinguishes root-relative links from relative and absolute links, letting us assign the required rules.

Content generated with pseudo-elements currently works only in Firefox, Netscape 6+ and Safari. Internet Explorer for Windows does not support generated content (yet?). Support for the CSS 3 specification is also not widespread.

See also

The recipe Setting font sizes and measurements for defining fonts in a web document, and the CSS 2.1 specification on generated content.

  

 

 

 

back to top