Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Usage of attr() CSS function
The attr() CSS function returns the value of an attribute of the selected element. It's commonly used with the content property in ::before and ::after pseudo-elements to display attribute values dynamically.
Syntax
attr(attribute-name)
Parameters
| Parameter | Description |
|---|---|
attribute-name |
The name of the HTML attribute whose value you want to retrieve |
Example 1: Displaying href Attribute
The following example displays the URL next to each link using the attr() function −
<!DOCTYPE html>
<html>
<head>
<style>
a::before {
content: " (" attr(href) ")";
color: #666;
font-size: 0.8em;
}
</style>
</head>
<body>
<h2>Information Resource</h2>
<p>Resource: <a href="https://www.tutorialspoint.com">TutorialsPoint</a></p>
<p>Search: <a href="https://www.google.com">Google</a></p>
</body>
</html>
The page displays links with their URLs shown in parentheses next to them in gray text.
Example 2: Displaying Custom Attributes
You can also use attr() with custom data attributes −
<!DOCTYPE html>
<html>
<head>
<style>
.tooltip {
position: relative;
cursor: help;
color: blue;
text-decoration: underline;
}
.tooltip::after {
content: attr(data-tooltip);
position: absolute;
bottom: 100%;
left: 50%;
transform: translateX(-50%);
background: #333;
color: white;
padding: 5px 10px;
border-radius: 4px;
white-space: nowrap;
opacity: 0;
pointer-events: none;
transition: opacity 0.3s;
}
.tooltip:hover::after {
opacity: 1;
}
</style>
</head>
<body>
<h2>Tooltip Example</h2>
<p>Hover over this <span class="tooltip" data-tooltip="This is a helpful tooltip!">text</span> to see the tooltip.</p>
</body>
</html>
A blue underlined text appears. When hovered, it shows a dark tooltip with the custom data-tooltip content.
Key Points
- The
attr()function can only be used with thecontentproperty - It works only with
::beforeand::afterpseudo-elements - Returns a string value of the specified attribute
- If the attribute doesn't exist, it returns an empty string
Conclusion
The attr() function provides a powerful way to display HTML attribute values dynamically in CSS. It's particularly useful for creating tooltips, showing URLs, and displaying custom data attributes without JavaScript.
Advertisements
