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
How to select elements with an attribute value containing a specified word with CSS?
The CSS [attribute~="value"] selector allows you to select elements where a specific attribute contains a particular word as part of a space-separated list of values. This is particularly useful when dealing with attributes like class, alt, or custom data attributes that may contain multiple words.
Syntax
[attribute~="word"] {
property: value;
}
How It Works
The ~= operator matches elements where the specified attribute contains the exact word as a complete, space-separated token. For example, if an element has alt="Online Tutorials Library", it will match [alt~="Tutorials"] but not [alt~="Tutorial"].
Example
The following example selects images with alt attributes containing the word "Tutorials" and applies an orange border −
<!DOCTYPE html>
<html>
<head>
<style>
[alt~="Tutorials"] {
border: 5px solid orange;
border-radius: 5px;
margin: 10px;
}
img {
display: block;
margin-bottom: 20px;
}
</style>
</head>
<body>
<img src="/videotutorials/images/tutor_connect_home.jpg" height="200" width="200" alt="Tutor Connect">
<img src="/videotutorials/images/tutorial_library_home.jpg" height="200" width="200" alt="Tutorials Library">
<img src="/videotutorials/images/coding_tutorials.jpg" height="200" width="200" alt="Online Tutorials Course">
</head>
</html>
Three images are displayed. The second and third images (with alt text containing "Tutorials") have orange borders with rounded corners, while the first image (alt="Tutor Connect") has no border styling applied.
Conclusion
The [attribute~="value"] selector is perfect for targeting elements based on specific words within space-separated attribute values. It provides precise matching for complete words rather than partial text matches.
