How to Interact with Object Attributes with CSS3’s attr() Function - dummies

How to Interact with Object Attributes with CSS3’s attr() Function

By John Paul Mueller

The attr() function is interesting because it lets you interact with any attribute of an object as part of a style. You see this function used in a number of unique ways on the Internet, even though it seems to be a well-kept secret for the most part.

One site that demonstrates a quick application that relies on attr() is The New Hotness: Using CSS3 Visual Effects. The following procedure demonstrates the attr() function in a simpler way so that you can better understand the few examples online that demonstrate it in a detailed way.

  1. Create a new HTML5 file with your text editor.

  2. Type the following code for the HTML page.

    <!DOCTYPE html>
     <title>Using the attr() Function</title>
     <link rel="stylesheet" href="Attr.CSS" />
     <h1>Using the attr() Function</h1>
     <p id="TestMe"

    All you have here is a heading and paragraph. Notice that the paragraph defines a standard attribute, id, and a non-standard attribute, TestText. The attribute you use for the attr() function need not be standard — you can define any attribute desired.

  3. Save the file as Attr.HTML.

  4. Create a new CSS file with your text editor.

  5. Type the following CSS style information.

     content: attr(TestText);

    The style begins by saying that the output from the style should appear before the tag referenced by TestMe as an id. It then sets the content of that area to the current value of the TestText attribute by using the attr() function.

  6. Save the file as Attr.CSS.

  7. Load the Attr example.

    The output is pretty much what you’d expect, Hello World. The attr() function can make it possible for you to hide and use all sorts of information in your pages, reuse information in different ways, or even perform debugging tasks.