CSS Attribute Selectors

Print Page

An attribute selector is used to select a HTML element using one of its attributes value. They allow one to write CSS for things already coded, without having to go back and add classes or ids.

An attribute selector matches elements on the basis of either the presence of an attribute, or the exact or partial match of an attribute value.

Standard Attribute Selector

Here’s a standard element selector, followed by an attribute selector.

a[rel="lightbox"] {
	background: #cc33ff;
}

The attribute selector is enclosed in square brackets, then the attribute name, a comparison operator, and finally the value to match in double-quotes.

Now, we will get into some more complex attribute selectors.

Starting With Selector

With the ^= operator, we can select attributes that starts with a specific value:

a[rel^="tech"] {
	background: #cc33ff;
}

That would would match ‘tech’, ‘technology’, ‘technicolor’, and any other words that starts with ‘tech’.

Another example:

<a href="http://sumtips.com">SumTips</a>
a[href^="http://sumtips.com"] {
	color: red;
}

That would style every link pointing to the domain ‘http://sumtips.com’. It can be the homepage or any sub-pages as well.

Ending With Selector

Using the $= operator, we can select attributes that ends with a specific value:

a[rel$="tech"] {
	background: #cc33ff;
}

Here ‘tech’ would match with something like ‘biotech,’ but not ‘technology’ or ‘technicolor’.

Another example for this operator can be to add icons for links to a particular file type.

a[href$=pdf] {
	background: url(pdf-icon.png) no-repeat;
	padding-left: 30px;
}

That would show a pdf icon to the left of all links pointing to a .pdf document.

Contains Value Selector

Using the *= operator, we can select attributes that contains a specific value anywhere in the attribute:

<p rel="polytechnic">Contains Value</p>

This will match any word that contains the letter ‘tech’.

p[rel*="tech"] {
	background: #cc33ff;
}

Space Separated Value Selector

Using the ~= operator, you will be able to select a value from a list.

<p rel="technology tech biotech">Space Separated</p>

This can be useful if you want to target any one of them.

p[rel~=tech] {
	color: #cc33ff;
}

Multiple Attributes Selector

If at any time, you want to select multiple attribute selectors in the same selector, it can be done as below:

<p rel="tech" title="Tech Updates">Multiple Attributes</p>
p[rel=tech][title$=Updates] {
	color: #cc33ff;
}