liveBook · Manning

Attr() function

As explained in Tiny CSS Projects

The CSS attr() function retrieves the value of an element's attribute for use in a CSS property value.

The CSS attr() function retrieves an element’s attribute value for use in a CSS property value. A practical use is adding mobile table labels from each cell’s data-name attribute. section 8.3.1

Labeling a responsive table

When a table header is moved offscreen for narrow screens, each cell can display its own label with a pseudo-element: td[data-name]::before { content: attr(data-name) ":"; float: left; }. The cell’s attribute value appears before its content while the original header remains available to assistive technologies. section 8.3.1

Listing 8.18 Displaying the contents of the data-name attribute
@media(max-width: 549px) {
  ...
  td {
    text-align: right;
    padding: 5px;
  }
  td[data-name]::before {
    content: attr(data-name) ":";
    float: left;
  }
}

Inspect the complete mobile rule showing attr() combined with a data attribute, the content property, and label alignment. section 8.3.1

The function takes an attribute name and returns its value; here, the value is combined with a colon inside content. The resulting labels can then be styled alongside other table text. section 8.3.1

How Tiny CSS Projects covers it

How deep it goes
Defines the function and demonstrates its CSS application, but does not examine broader value types or browser-specific behavior.
Examples
Demonstrates data-name labels displayed before cells in a mobile checkout table.
What it assumes
Assumes basic HTML attributes and CSS selectors while demonstrating pseudo-elements and the content property in context.
What you can do after
Apply it via CSS to display an element’s attribute value through a pseudo-element and the content property.
How it connects
Connects HTML attributes with pseudo-elements, the content property, media queries, and responsive table layouts.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Tiny CSS Projects. The section links point to the parts of the book it draws on.