AD
Episode
233
Interview
Web News

CSS Attribute Selectors & Custom Attributes

Recorded:
January 31, 2023
Released:
February 8, 2023
Episode Number:
233

CSS attribute selectors are a lot more powerful than I thought! I wasn't aware that they could not only select elements based on the presence of an attribute, or the presence of an attribute with a specific value, but that they could also "filter" through that attribute value by placing specific parameters on them using just CSS. In this episode, Matt and Mike discuss these "advanced attribute selectors" and cap the episode off by discussing another powerful CSS feature - custom attributes, done the right way!

Listen

Also available on...
...and many more, check your podcast app!

Who’s in This Episode?

Show Notes

Topics & Timestamps

  • [ Basic] Attribute Selectors | 00:01:37
    - Square brackets in CSS
    - Selects elements based on the presence of a specified attribute
    - Selects elements based on the presence of a specified attribute with a particular value
  • Advanced Attribute Selectors | 00:03:07
    The term "advanced attribute selectors" isn't official in any way, we're using it for our own organization
    - Adding specific characters after the attribute name allows for more granular/advanced selecting based on the attribute value
    - The characters include: Tilde ~, Vertical Bar |, Caret ^, Dollar Sign $, Asterisk *
    - Tilde selects elements that contain a specific space-separated word in the value of a specified attribute
    - Vertical bar selects elements that have exactly the specified value or specified value separated by a hyphen
    - Caret selects elements whose attribute value started with the specified value
    - Dollar sign is the opposite of the caret, selecting elements whose attribute value ends with the specified value
    - Asterisk (wildcard) selects elements based on if an attribute value contains a specific value (does not have to be a whole word)
  • Custom Attributes | 00:14:21
    - You can add your own attributes with their own unique name, and even misuse existing attributes with little consequence, but this is discouraged
    - Performing this discouraged behavior does not often break a site (ie the site won't crash) but it does make your HTML invalid, and can be problematic for future developers and accessibility tooling (ie screen readers)
    - Instead, if you need custom attributes, simply write a data- followed by the name you want
    - These are commonly referred to as data-* attributes
    - You can have more than one data attribute
    - Data attributes have their own JavaScript API (using the getAttribute method)
    - You can have JSON data inside a data attribute, you can pull and parse the data as needed

Sources