DEV Community

Cover image for CSS Attribute Selectors Cheat Sheet
Adarsh Goyal
Adarsh Goyal

Posted on

CSS Attribute Selectors Cheat Sheet

CSS [attribute] Selector

Simplest of all the selectors and requires just the attribute name in the parameters. All the elements in the web page that contains this attribute name will be selected to apply the styling.

The following code performs CSS styling on the “p” elements that have the “lang” attribute:

<style>
  p[lang]{
      color: red;
      font-size: 20px;
  }
</style>
<p lang = “en”>Your Text</p>
<p>Your Text</p>
Enter fullscreen mode Exit fullscreen mode

CSS [Attribute ~= “value”] Selector

CSS [Attribute ~= “value”] can select the element if it includes the word “value” in the attribute specified. For example, the following code looks for the value “shirt” in the attribute “title”.

<style>
    p[title ~= "shirt"]{
      color: red;
      font-size: 20px;
    }
</style>

<p title="blue shirt">Your Text</p>
<p title="red shirt">Your Text</p>
<p title="hoodie">Your Text</p>
Enter fullscreen mode Exit fullscreen mode

The above code selects the first two paragraphs since they have a shirt in their title, which is the target attribute.

CSS [attribute |= “value”] Selector

CSS[attribute |= “value”] selector selects all those attribute values that start with the word “value”.

Note: CSS[attribute |= “value”] selector works only when the value is either a single word in the attribute such as only “shirt” or is hyphenated as “shirt-blue”. White space in between will not be selected by the CSS for styling.

The shortcoming of CSS[attribute |= “value”] is fulfilled by the CSS[attribute ^= “value”] selector.

CSS[attribute ^= “value”] Selector


<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>Web Template</title>
      <style>
      p[title ^= "shirt"]{
        color: red;
        font-size: 20px;
      }
      </style>
  </head>
  <body>
    <br><br>
        <br><br>
    <p title="shirt-blue">Your Text.</p>
    <p title = "shirt red">Your Text.</p>
    <p title = "hoodie">Your Text.</p>
  </body>
</html>

Enter fullscreen mode Exit fullscreen mode

CSS [attribute *= “value”] Selector

This selector works like the regular expression checker which selects every element with the target attribute having value composed of “value”. The value need not be a whole word. The selector works even if the “value” is a part of the attribute value.

I hope this CSS selectors cheat sheet helps you ahead in your professional career and if there are any suggestions, feel free to comment them down to help us refine the post for good.

Thank you for reading!💃🏻

https://adarshgoyal.com/
twitter
linkedin

The cover image of this article is generated using DALL-E.

Top comments (0)