Friday, 15 November 2024

Using the |= Operator to Match Prefixes and Hyphenated Values in CSS

The |= operator matches elements whose attribute value either exactly equals the specified value or starts with the specified value followed by a hyphen. This is typically used for language codes or other hierarchical data where values might be prefixed with a common identifier.

[data-lang|="en"] {
   color: green;
   font-weight: bold;
}

The CSS selector [data-lang|="en"] targets elements with an attribute named data-lang whose value is either exactly "en" or starts with "en" followed by a hyphen (-).

prefixHypernated.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Custom Attribute Selector Test</title>
    <style>
        /* Selects elements with data-lang attribute starting with 'en' or exactly 'en' */
        [data-lang|="en"] {
            color: green;
            font-weight: bold;
        }
    </style>
</head>
<body>
   <p data-lang="en">This is in English.</p>
   <p data-lang="en-US">This is in en-US English.</p>
   <p data-lang="en_US">This is in en_US English.</p>
   <p data-lang="fr">This is in French.</p>
</body>
</html>

 

In the above example,

1.   The <p data-lang="en"> and <p data-lang="en-US"> should be styled with green text.

2.   The <p data-lang="en_US"> , <p data-lang="fr"> should not be styled.

 

Above snippet generate below screen.


 

Previous                                                    Next                                                    Home

No comments:

Post a Comment