Multiple Attribute Values

Chris Coyier //

Elements can have multiple class names. For instance:

<div class="module accordion expand"></div>

Then in CSS, you could match that element based on any one of them:

/* All these match that */
.module { }
.accordion { }
.expand { }

You can limit your selectors to match only if several of them are present, for example:

// Will only match if element has both
.accordion.expand { }

But what about other attributes?

Class names are unique in the ability outlined above. Other attributes are not treated as "multiple values" just because they have a space in them. For instance:

<div data-type="module accordion expand"></div>

This element just has a data-type attribute with a value of "module accordion expand", not three unique values "module", "accordion" and "expand". But let's say we wanted to be able to select elements based on individual values like we can with class names.

We could do it by using a "*" substring matching attribute selector which will match if the provided string appears anywhere in the value:

[data-type*="module"] {

}

or only match when multiple of specific "values" are present:

[data-type*="accordion"][data-type*="expand"] {

}

Ever better, use the whitespace separated selector (e.g. [data-type~="expand"]). That way you won't get burned by something like "expand" matching "expander" when you didn't want to.

[data-type~="accordion"][data-type~="expand"] {

}

View Demo

Works in IE7+ (because IE 7 was first IE to support attribute selectors)