CSS [attribute~=value] Selector

The [attribute~=”value”] selector is used to select those elements whose attribute value contains a specified word. The “value” must be present in the attribute as a separate word and not as part of the other word i.e. if [title~=Beginner] is specified then all elements with Beginner title get selected.

Syntax:

[attribute~=value] {
    // CSS property
}

Example 1: In this example, The CSS selector [class~=”Beginner”] targets elements with a class attribute containing the word “Beginner” and applies green background color and white text color.

html




<!DOCTYPE html>
<html>
 
<head>
    <style>
        [class~="Beginner"] {
            background: green;
            color: white;
        }
    </style>
</head>
 
<body style="text-align:center;">
 
    <div class="Beginner Class">
        First div Element
    </div>
 
    <div class="w3wiki">
        Second div Element
    </div>
 
    <div class="My Beginner">
        Third div Element
    </div>
 
    <div class="MyBeginner">
        Fourth div Element
    </div>
</body>
 
</html>


Output:

Example 2: In this example, The CSS selector [class~=Beginner] targets elements with a class attribute that contains the word “Beginner” and applies a blue solid border.

html




<!DOCTYPE html>
<html>
 
<head>
    <title>
        CSS [attribute~=value] Selector
    </title>
 
    <style>
        [class~=Beginner] {
            border: 5px solid blue;
        }
    </style>
</head>
 
<body>
    <h2 style="text-align:center">
        [attribute~=value] Selector
    </h2>
 
    <img src=
"https://media.w3wiki.net/wp-content/uploads/w3wiki-logo.png"
         class="Beginner Class"
         alt="gfg">
 
    <img src=
"https://media.w3wiki.net/wp-content/uploads/Beginner-25.png"
         class="Beginner"
         alt="Beginner">
 
    <img src=
"https://media.w3wiki.net/wp-content/uploads/w3wiki-10.png"
         class="w3wiki"
         alt="gfg">
</body>
 
</html>


Output:

Supported Browsers: The browser supported by [attribute~=value] selector are listed below:

  • Google Chrome 4.0
  • Internet Explorer 7.0
  • Firefox 2.0
  • Safari 3.1
  • Opera 9.6


Contact Us