0% completed
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.
selector::before { content: attr(attribute-name); }
Explanation:
::before
or ::after
) to insert this value as content.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>
.
Explanation:
.box
element has a custom attribute data-label
with the value "Special Box"..box::before
uses attr(data-label)
to insert the attribute's value into the content, preceded by the text "Label: ".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.
Explanation:
<a>
element has a title
attribute with the value "Learn More About Our Services".a::after
uses attr(title)
to retrieve the title attribute and insert it into the content, wrapped in parentheses.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.
.....
.....
.....