Read more

CSS: Set content from other attributes

Arne Hartherz
February 07, 2013Software engineer at makandra GmbH

You can use the content CSS attribute to set an element's content -- which is especially useful for the :before and :after pseudo elements:

a:before {
  content: 'Click me: ';
}
Illustration book lover

Growing Rails Applications in Practice

Check out our e-book. Learn to structure large Ruby on Rails codebases with the tools you already know and love.

  • Introduce design conventions for controllers and user-facing models
  • Create a system for growth
  • Build applications to last
Read more Show archive.org snapshot

The above example would prepend "Click me:" to any link on the page.

Note that you can also refer the contents of other attributes of the element. So, if your links have a helpful title set, you could do this:

a:before {
  content: attr(title) ": ";
}

There also is a jsFiddle Show archive.org snapshot for the example above.

As a bonus, here is a (hacky) snippet that shows the URL of each link when hovering:

a:hover:after {
  content: attr(href);
  white-space: nowrap;
  position: absolute;
  background: #fff;
  z-index: 99;
}
Posted by Arne Hartherz to makandra dev (2013-02-07 15:49)