Checkout my Getting Started with React video course on Skillshare. It is 100% free.

CSS Attribute selector – case insensitive option and select by multiple attributes

Some days ago I have written a short intro to the attribute selector in CSS. I have found out two new tricks for this selector that I want to share with you today.

Case-insensitive CSS attribute selectors

First, the attribute selector is case sensitive. This can be especially troublesome for the data- attributes.

Take for example the following set of tags:

<div data-status="OPEN">First widget</div>
<div data-status="open">Second widget</div>
<div data-status="open">Third widget</div>

Give the case sensitivity the following selector will target only the first div.

// will target only the first div
div[data-status="OPEN"] { color: red;} 

But, we have the i flag in the attribute selector. And with it, we can target tags no matter the capitalization.

// will target all the divs
div[data-status="OPEN" i] { color: red;} 

Pay atattion to the fact that the i flag will not work in IE.

CSS attribute selector for multiple tags

The second trick is the ability to target tags based on multiple attributes.

For example, if we want to target all the h1 tags that have both a rel="main subject" and a title="important note":

<h1 rel="main subject" title="important note">Multiple Attributes</h1>    

Then we can write

h1[rel="main subject"][title^="important note"] { 
    color: red; 
}

Learned this one from the excellent CSS Tricks article: The Skinny on CSS Attribute Selectors.