Lesson Overview

In the previous lesson on CSS Syntax, you learned about basic element selectors (which are also called type selectors). There are other types of selectors you can use if you want to do more than select all elements of a certain type - you probably have already learned about class selectors and id selectors, also. Attribute selectors allow you to select and style elements based on their attributes: you can select elements that contain a certain attribute, or you can select elements that have a certain attribute value.

Pre-Requisites

Make sure that you've worked through the previous tutorial, CSS Syntax before proceeding through this lesson.

Attribute Selectors

You can also select elements to style based on whether or not they have certain attributes, or if those attributes have certain values. For example, what if you want to style all <input> elements that are text fields, but not checkbox or radio buttons (type="text" but no other types)? What if you want to select and style all <label> elements that have a for="" attribute set, but not the <label> elements that have no for="" attribute? Attribute selectors allow you to do that!

An attribute selector is always enclosed inside square brackets, after the element it is attached to. For example:

label[for] { ... }

The above example selects and styles all <label> elements that have a for="" attribute, regardless of the attribute's value.

CodePen: Attribute Selectors

See the Pen Attribute Selectors 1 by Wendi Jollymore (@ProfWendi) on CodePen.

If you want to be specific about the value an attribute contains, you can use the attribute-value selector. The syntax is similar, you just add an equals sign (=) followed by the value you're selecting:

input[type=text] { ... }
/* or you can use quotes */
input[type="text"] { ... }

The example above will select and style only <input> elements that have type="text". Notice that you don't have to put quotes in the attribute-value selector.

CodePen: Attribute-Value Selectors

See the Pen Attribute Selectors 2 by Wendi Jollymore (@ProfWendi) on CodePen.

What if you want to do this with a partial match? You can use the *= operator instead of the = operator.

div[class*="box"] { ... }

The above example will select and search for all DIV elements with a class attribute that contains the text "box". So it will select elements with class="round box", class="abcbox-def", and class="box".