O'Reilly logo

Learning PHP, MySQL, JavaScript, and CSS, 2nd Edition by Robin Nixon

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Attribute Selectors

In the previous chapter I detailed the various CSS attribute selectors, which I will now quickly recap. Selectors are used in CSS to match HTML elements, and there are 10 different types, as detailed in Table 19-1.

Table 19-1. CSS selectors, pseudoclasses, and pseudoelements

Selector type

Example

Universal selector

* { color:#555; }

Type selectors

b { color:red; }

Class selectors

.classname { color:blue; }

ID selectors

#idname { background:cyan; }

Descendant selectors

span em { color:green; }

Child selectors

div > em { background:lime; }

Adjacent sibling selectors

i + b { color:gray; }

Attribute selectors

a[href='info.htm'] { color:red; }

Pseudoclasses

a:hover { font-weight:bold; }

Pseudoelements

p:first-letter { font-size:300%; }

The CSS3 designers decided that most of these selectors work just fine the way they are, but three enhancements have been made so that you can more easily match elements based on the contents of their attributes.

Matching Parts of Strings

In CSS2 you can use a selector such as a[href='info.htm'] to match the string 'info.htm' when found in an href attribute, but there’s no way to match only a portion of a string. However, CSS3 comes to the rescue with three new operators: ^, $, and *. If one of these directly precedes the = symbol, you can match the start, end, or any part of a string, respectively.

The ^ operator

For example, the following will match any href attribute whose value begins with the string 'http://website':

a[href^='http://website'] ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required