Using the data attribute as content in CSS

28 September 2011

Today CSS master Joshua Hibbert pointed out that it's possible to use values from data attributes as value in CSS content. He created an awesome CSS-only cardcase on jsfiddle which utilizes this CSS3 feature.

<p class="credit-card" data-title="Credit Card"></p>

The content in this data attribute,title in this case, but this can be everything you want, is rendered in the :after pseudo class:

.debit-card:after {
    content: attr(data-title);
    font-size: 12px;
    left: 6px;
    position: absolute;
    top: 1px;

A second attribute can be used in the :before pseudo-class, so with this technique you're able to add two extra "elements" without adding extra HTML markup.

Before, if you wanted to place three different texts in one element, you'd have to do something like this:

<div class="credit-card">
  One milion dollars!
  <div class="title">Credit Card</div>
  <div class="address">Address, telephone and e-mail</div>

Which can be way cleaner and less markup with the data attributes:

<div class="credit-card" data-title="Credit Card" data-address="Address, telephone and e-mail">One milion dollars!</div>

Read more about the powerfull and versatile HTML5 data attribute in the "using the HTML5 data attribute" article.
You must have JavaScript enabled to use this form!

Leave a comment!

  1. Your mail is safe with me. It's only only used to display your Gravatar image!


  1. Gravatar


    31 October 2012

    Hi Melanke, Sadly that is not possible (with CSS alone). CSS is supposed to be used for styling only. Changing/setting parameters of elements is something that better be done server side (via PHP, ASP, Coldfusion, etc) or via Javascript.

    I suggest you'd use javascript for a solution. JS might be a little difficult if you don't have any experience with it, but using a JS library like jQuery can make thing much easier.

  2. Gravatar


    30 October 2012


    I was wondering...
    There is a way to change html attributes?
    something like:

    this[value=some text here]


    this[data-price=some data]

    would be nice

  3. Gravatar

    Robert Burden

    19 October 2012

    the JSfiddle link is dead :(