close
The Wayback Machine - https://web.archive.org/web/20250211080201/https://www.geeksforgeeks.org/css-attr-function/
Open In App

CSS attr() Function

Last Updated : 30 Aug, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

The attr() function is an inbuilt function in CSS that returns the value of an attribute of the selected elements.

Syntax: 

attr( attr_name )

Parameter: This function accepts a single parameter attr_name which is used to hold the name of the attribute in an HTML element. It is a mandatory parameter.

Return Value: This function returns the value of the attribute of selected elements.

Example: The below example illustrates the attr() function in CSS:

html
<!DOCTYPE html>
<html>

<head>
    <title>attr function</title>
    <style>
        a:before {
            content: attr(href) " =>";
        }
        
        a {
            text-decoration: none;
        }
        
        .gfg {
            font-size: 40px;
            color: green;
            font-weight: bold;
        }
        
        body {
            text-align: center;
        }
    </style>
</head>

<body>
    <div class="gfg">GeeksforGeeks</div>
    <h1>The attr() Function</h1>
    <a href=
"https://www.geeksforgeeks.org">
        GeeksforGeeks
    </a>
</body>

</html>

Output: 

BERJAYA

Supported Browser:

  • Google Chrome
  • Edge
  • Firefox
  • Opera
  • Safari  

CSS attr() Function – FAQs

What does the attr() function do in CSS?

The attr() function is used to retrieve the value of an HTML attribute and use it in the content property of CSS, mainly for displaying attribute values in generated content.

Can attr() be used with properties other than content?

Currently, attr() is primarily supported for the content property and is not widely supported for other CSS properties like width or height.

How do you use the attr() function in CSS?

To use attr(), define it within the content property, such as p::after { content: attr(data-info); } to display the value of the data-info attribute.

Does attr() work with custom attributes?

Yes, attr() can retrieve values from custom attributes like data-* attributes, making it useful for dynamic content styling.

What are the limitations of the attr() function in CSS?

The main limitation is its restricted use to the content property, and it cannot dynamically update styles based on attribute changes without JavaScript.


Practice Tags :

Similar Reads

three90RightbarBannerImg