Using CSS’s Attribute Selectors

Did you know that in CSS, you can select elements based on their attribute or attribute values? This is a super useful way to select specific elements that have no class or ID distinctions but have attribute values, or to select all elements that have nothing else in common with each other besides their attribute values. It’s pretty neat.

To select any div element with a style attribute (regardless of the attribute’s value) and change the width to 100%, the CSS would be is very simple. Check it out below:

Join us in our newest publication:
   width: 100%;

As you can see, the syntax is pretty easy to follow. You simply put the attribute in [] brackets following the element selector (if you choose to include one).

The syntax changes a bit if you want to select an item based on its attribute and value. For this kind of selection, you’ll need to put the attribute in brackets and the value next to it with an = sign and within quotations, just like you would write it in the HTML. Let’s say you wanted to select all p elements that had a title value of blue. The HTML tag would probably look something like this:

<p title="blue">

So to select all of these specific p elements and change their text color to blue, you’ll need your CSS selector to look like this:

   color: blue;

If you want to select all items only by their attributes regardless of the HTML element they’re attached to, you can drop the element selector and just include the content of the brackets. So if you want to select all elements that have a target attribute and change the font size, it would look like this:

   font-size: 30px;

Stay tuned for part two of our CSS attribute selector tutorial, coming later this week!


Share and Enjoy !

0 0