Home · Examples · The attr(x) function

The attr(x) function

Plenty of web sites refer to this example when describing what the attr(x) function does. In general, it justs pulls the attribute value out of an element, and returns it as a string. A string that can be used, however you please.

@media print {
  a::after {
    content: attr(href);
  }
}

Sure, I'll admit - showing users what the URL of a link was, AFTER the page has been printed, can be quite useful. For example:

Though, it doesn't look all that good crammed up against the right side of a link. And what if we have "back to top" (section anchored) links inside/throughout the page?  In this case it would be useless to the user to see "#top" as the URL, to remedy this, we can:

1. Make it exclude links which begin with a pound sign:

@media print {
  a:not([href^='#'])::after {
    content: attr(href);
  }
}

2. Make it enclose the href value with parenthesis, and give it some spacing so it'll look pretty! grin

@media print {
  a:not([href^='#'])::after {
    background-color: #FFF;
    padding: 3px;
    content:"( " attr(href) " ) " ;
  }
}

So our finished result should look something like this:

eBay (http://www.ebay.com)

And thats all folks. If you have suggestions, chime in.

Notes:
Internet Explorer (even version 7) doesn't support the the ::before and ::after pseudo elements.

Jul 07, 2007

Comments

This article hasn't been commented yet.

Write a comment

* = required field

:

:

:


2 + 7 =