CSS: Tips and tricks when using CSS Attribute Selectors
Last updated: 3rd July 2020Here are some tips I made about CSS Attribute Selectors. Hope it's helpful!
Demonstration of CSS Attribute Selectors
Here's the element we're trying to match against:
<a href="https://umaar.com/dev-tips">Dev Tips</a>
This selector below matches the element since the element has an href attribute:
a[href] {}
The selector below matches too as the element has this exact href attribute value:
a[href="https://umaar.com/dev-tips"] {}
The href attribute value does include the string .com, so the selector below is a matching selector:
a[href*=".com"] {}
The href value does start with the string https:
, therefore this selector below matches:
a[href^="https:"] {}
The href value ends with the string /dev-tips
, so this selector below also matches:
a[href$="/dev-tips"] {}
The special i
operator
There is also a special operator you can use in CSS Attribute Selectors:
The operator is i
and here's how it works.
The element below is the one we're trying to match:
<a href="https://umaar.com" title="Home">Home</a>
⚠️ This selector below will not match due to case sensitivity. Notice the element uses the string Home
but the CSS selector specifies home
- in lowercase:
a[title="home"] {}
✅️ This selector below will match because the i
treats it as case insensitive:
a[title="home" i] {}
Pictures and tweets
Here are some pictures of the code shown above, if you prefer that at all.
And here are the two tweets where I posted the pictures, tweet 1 and tweet 2.