Targeting Elements with Attribute Tilde Selectors in CSS


[attributename~="value"]

In CSS, the [attribute-name~="value"] selector is an attribute selector that targets HTML elements based on the presence of a specific attribute with a value that is part of a space-separated list. This selector allows you to select elements where the specified attribute contains a value within a list of values separated by spaces.

Selector Syntax: To use the [attribute-name~="value"] selector, you enclose both the attribute name and the attribute value within square brackets, separated by the tilde (~) character.

[attribute-name~="value"] {
    /* CSS rules */
}

Source Code :

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Attribute Selector</title>
    <style>
      /*
      p[class~="title"] {
        color: orange;
      }*/
      [class~="title"] {
        color: orange;
      }
    </style>
  </head>
  <body></body>
  <h3>[attributename~="value"] selector</h3>
  <p>Value matches attribute in space separated list.</p>
  <p class="title">Tutor Joes - P1</p>
  <p class="titleColors">Tutor Joes - P2</p>
  <p class="black title red">Tutor Joes - P3</p>

  <div class="title">Tutor Joes - D1</div>
</html>

Live Preview

This CSS rule uses an attribute selector with the ~= operator to select elements that have a class attribute containing the value "title" as one of the space-separated values within the attribute.

[class~="title"]: This is the selector part of the rule. It targets all elements that meet the condition specified within the square brackets.

[class~="title"]: This is the attribute selector. It specifies the condition for selecting elements. In this case, it's looking for elements with a class attribute containing the value "title" as one of the space-separated values within the attribute.

color: orange;: This is the style declaration. It sets the color property of the selected elements to orange.

So, this CSS rule will select all elements that have a class attribute containing "title" as one of the space-separated values within the attribute. For example, it would match elements like <div class="section-title">, <h1 class="title">, and <span class="custom-title">, as long as "title" is present as one of the values within their class attributes. When selected, these elements will have their text color changed to orange.


CSS Tutorial


Properties Reference


Cascading Style Sheet


Flexbox Tutorial


CSS Grid Tutorial


Transitions Properties


CSS Properties with Examples


CSS Selectors


CSS Pseudo Elements


CSS Attribute Selectors


Input Pseudo Classes


CSS Examples


CSS Animation Projects