CSS: Using Attribute Selector
Greetings! I am currently learning CSS and came across attribute selectors. I am wondering:
- When it is better to use attribute selectors instead of the usual selectors that uses id/class.
- If it is efficient to use on a website. I have read that class selectors are usually faster.
Thank you very much!
3 Replies
Anything that talks about classes being faster than attribute selectors was either written in the late 90s, or is referencing articles written in the late 90s. They're essentially the same.
Some of it comes down to how you want to work. If you watch enough of my videos, you'll see me using them for more than most people do.
A lot of the time, it's most handy if you are doing any type of manipulation with JavaScript though. It's slightly easier to get, add, or remove, and toggle attributes compared to classes.
Because many CSS styles are based on IDs and classes, it's best to not use them for JS hooks and classes can change. A popular JS "hook" is to use
data-[js-event]
attribute so you can specifically target the element. And, as a bonus, data-*
attributes can have a value, so if you need to pass simple info to JS you can do so there.Its helpful to combine attribute selectors (although these work woth classes and ids too) with advanced selectors. Then you can style certain elements certain ways. Like say you had an <a> that oprns in a new window; maybe you want all of those links to have a pseudo element with an icon that indicates it opens in a new window
Examples:
Not a popular opinion but I also like to use
[id=IDSelector]
instead of #IDSelector
to avoid raising specificity unnecessarily. But this is less and less needed with :where()
selectors and @layer
these days