CSS selectors can be pesky, but so can design requirements. When it comes time to build a website, having a full arsenal of selectors at your disposal can be an invaluable skill.

Attribute Selectors

Attribute selectors come in handy quite often when dealing with third party plugins or when you need to select a specific item, but may not be able to add a class.

Let’s give an example: Say we have a plugin that uses aria-expanded attribute to denote whether a given tab is opened or closed. Say perhaps that we want to change the font weight on the header of a tab aria-expanded is set to true. The situation is outlined in the code below:

<div class="tabs">
  <div class="tab" data-expanded="false">
	<h3>
  		Tab 1
  	</h3>
  </div>
  <div class="tab" data-expanded="true">
  	<h3>
  		Tab 2
  	</h3>
  </div>
  <div class="tab" data-expanded="false">
  	<h3>
  		Tab 3
  	</h3>
  </div>
</div>

Notice how apart from data-expanded=”true” there is nothing we can use here to style this tab. This is the perfect time to use an attribute selector.

Attribute selectors can be used in several ways:

/* Select all elements with an attribute equal to a value */
[attribute=value] {
	font-weight: 700;
}

/* Select all elements with an attribute containing a value */
[attribute*=value] {
	font-weight: 700;
}

/* Select all elements with an attribute beginning with a value */
[attribute^=value] {
	font-weight: 700;
}

/* Select all elements with an attribute ending with a value */
[attribute$=value] {
	font-weight: 700;
}

So combining the above with our current situation, we would get the code below:

div.tab[data-expanded="true"] h3 {
    font-weight: 700;
}

This will find any h3 inside a div with the class tab and attribute data-expanded set to true, and make it bold. Lastly, here is our code with everything put together:

<style>
div.tab[data-expanded="true"] h3 {
    font-weight: 700;
}
</style>

<div class="tabs">
  <div class="tab" data-expanded="false">
	<h3>
  		Tab 1
  	</h3>
  </div>
  <div class="tab" data-expanded="true">
  	<h3>
  		Tab 2
  	</h3>
  </div>
  <div class="tab" data-expanded="false">
  	<h3>
  		Tab 3
  	</h3>
  </div>
</div>