avatar

Andres Jaimes

CSS – Attribute selectors

By Andres Jaimes

Attribute selectors allow you to select CSS elements based on their attributes or values.

For example, if you want to select an image named “great.gif” you can do it by using the following rule:

img[src="great.gif"] { border: 3px solid #000; } 

There are four types of selectors.

By attribute. The following example will select all the images that contain the given attribute:

img[title] { border: 3px solid #000; }
img[width] { border: 3px solid #000; }
img[alt] { border: 3px solid #000; } 

By value. This will look for all elements that have a “src” attribute with the given value:

img[src="great.png"] { border: 3px solid #000; } 

By space separated instances of a value. The following example will select all images that include the “alt” attribute and a value that includes the word “great”.

img[alt~="great"] { border: 3px solid #000; } 

By hyphen separated instances of a value. This example will select all images that include the “title” attribute and has a hyphen separated list that includes the word “great”.

img[title|="great"] { border: 3px solid #000; }