CSS for Web Development

0% completed

Previous
Next
CSS attr() Function

The CSS attr() function allows you to retrieve an element's attribute value and use it in your styles. This is most commonly used with pseudo-elements like ::before or ::after to display attribute content directly on the page. With the attr() function, you can add dynamic text content without altering your HTML.

Syntax

selector::before { content: attr(attribute-name); }

Explanation:

  • attr(attribute-name): Retrieves the value of the specified attribute from the element.
  • Commonly used with pseudo-elements (::before or ::after) to insert this value as content.

Example 1: Displaying a Data Attribute Before an Element

In this example, we use the attr() function to display a custom data attribute from a <div> element. The pseudo-element inserts the value of the data-label attribute before the content of the <div>.

HTML

. . . .

Explanation:

  • The .box element has a custom attribute data-label with the value "Special Box".
  • The CSS rule for .box::before uses attr(data-label) to insert the attribute's value into the content, preceded by the text "Label: ".
  • The pseudo-element displays this label above the box content with bold styling and a red color.

Example 2: Inserting the Title Attribute in a Link

This example shows how to use the attr() function to display the value of a title attribute from an <a> element. The pseudo-element is used to append the title next to the link text for additional context.

HTML

. . . .

Explanation:

  • The <a> element has a title attribute with the value "Learn More About Our Services".
  • The CSS rule for a::after uses attr(title) to retrieve the title attribute and insert it into the content, wrapped in parentheses.
  • This additional text appears immediately after the link, providing extra context without modifying the HTML content.

These examples show how the CSS attr() function can be used with pseudo-elements to dynamically display attribute values, adding flexible and context-sensitive content to your web pages without extra HTML markup.

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next