Exploring Conditional Attribute Selectors in CSS


[attributename|="value"]

The [attribute|="value"] selector is used to select elements with the specified attribute, whose value can be exactly the specified value, or the specified value followed by a hyphen (-).

Syntax

[attributename|="value"]

Represents elements with an attribute name of attr whose value can be exactly value or can begin with value immediately followed by a hyphen. It is often used for language subcode matches.

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|="text"] {
        color: red;
      }
    </style>
  </head>
  <body>
    <h3>[attributename|=value] Selector</h3>
    <p>Attribute begin with value OR is first in a dash separated list</p>

    <p class="text">Tutor Joes - P1</p>
    <p class="text-small">Tutor Joes - P2</p>
    <p class="sample-wtext-value">Tutor Joes - P3</p>
    <p class="text-down">Tutor Joes - P4</p>
    <p class="textdown">Tutor Joes - P5</p>
  </body>
</html>

Live Preview

This CSS rule is using an attribute selector with the |= operator to select <p> elements whose class attribute contains the word "text" as a whole word or as part of a hyphen-separated word.

p[class|="text"]: This is the selector part of the rule. It targets all <p>elements that meet the condition described within the square brackets.

[class|="text"]: This is the attribute selector. It specifies the condition for selecting elements. In this case, it's looking for elements with a class attribute that contains "text."

color: red;: This is the style declaration. It sets the color property of the selected <p> elements to red.

So, in summary, this CSS rule selects all <p> elements that have a class attribute containing the word "text," whether it's a standalone class or part of a hyphen-separated class. When selected, the text inside these <p> elements will be displayed in red.


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