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

Select tags by attribute in CSS

It is possible in CSS to select tags just based on the value of an attribute. Take for example for following HTML:

<input type="email" placeholder="Your email" />
<input type="password" placeholder="Your password" />
<input type="password" placeholder="Confirm password" />

If you want to select just the inputs that are of type passwod we will just need the following code:

input[type="password"] {
    background-color: yellow; }
}

This is the attribute selector in CSS.

But what if we want to target just the links that have an URL attached to them:

<a href="google.com">Search</a>
<a onclick="alert('hi')">Show alert</a>
<a href="js-craft.io">Learn CSS</a>

Here we don't have a constant index-value pair like in the first example, but we can say:

a[href] { 
    background-color: yellow; 
}

And wait there is even more we can do:

  • [test~="foo"] : Checks if the value of the attribute test contains the word foo no matter of the position.
  • [test|="foo"] : Checks if the value of the attribute test starts with the word foo.
  • [test^="foo"] : Checks if the value of the attribute test has the first 3 letters foo.
  • [test$="foo"] : Checks if the value of the attribute test ends with the word foo.