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
Return the value of an attribute of the selected element using CSS
The attr() CSS function returns the value of an attribute of the selected element and is commonly used with the content property in pseudo-elements to display attribute values as text content.
Syntax
selector::before,
selector::after {
content: attr(attribute-name);
}
Example: Displaying Link URLs
The following example uses the attr() function to display the URL of a link after the link text −
<!DOCTYPE html>
<html>
<head>
<style>
a::after {
content: " (" attr(href) ")";
color: #666;
font-size: 0.9em;
}
</style>
</head>
<body>
<h2>Information Resource</h2>
<p>
Resource: <a href="https://www.tutorialspoint.com">TutorialsPoint</a>
</p>
</body>
</html>
A heading "Information Resource" followed by text "Resource: TutorialsPoint (https://www.tutorialspoint.com)" where the URL appears in gray text after the link.
Example: Using Custom Attributes
You can also use attr() with custom data attributes to display additional information −
<!DOCTYPE html>
<html>
<head>
<style>
.tooltip {
position: relative;
border-bottom: 1px dotted #333;
}
.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;
font-size: 12px;
white-space: nowrap;
opacity: 0;
pointer-events: none;
transition: opacity 0.3s;
}
.tooltip:hover::after {
opacity: 1;
}
</style>
</head>
<body>
<p>Hover over this <span class="tooltip" data-tooltip="This is additional information">text</span> to see a tooltip.</p>
</body>
</html>
Text with a dotted underline appears. When hovering over "text", a dark tooltip showing "This is additional information" appears above it.
Conclusion
The attr() function is useful for displaying attribute values in pseudo-elements, commonly used for tooltips, showing URLs in print styles, or displaying custom data attributes as visible content.
Advertisements
