Forum Moderators: not2easy
3.2. Attribute Selectors
Attribute Selectors [w3.org] allow CSS authors to specify rules that match elements which have certain attributes defined in the source document, the first 4 were available in CSS2.1 and the second three are new to CSS3. support for them all is very good even in IE7.
The existing 2.1 Attribute Selectors
Syntax: [att]
Syntax: [att="value"]
value". Syntax: [att~="value"]
value". Syntax: [attŠ="value"] (1)
Attribute Selectors New to CSS3
Syntax: [att^="value"]
value". Syntax: [att$="value"]
value". Syntax: [att*="value"]
value". Example:
(2)
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>CSS2.1 and CSS3 Attribute Selector Tests</title>
<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1">
<style type="text/css" media="screen">
div {border: 1px solid #abc; margin: 10px 0;}
p {margin: 10px;}
/* CSS2.1 attribute Selectors */
p[valign] {background: #ffa;}
p[bgcolor="red"] {background: #dad;}
p[class~="two"] {background: #aad;}
p[lang¦="x"] {background: #aaa;} /* change this pipe to an unbroken one */
/* New to CSS3 Attribute Selectors */
p[class^="one"] {background: #ffa;}
p[class$="2"] {background: #dad;}
p[class*="ee"] {background: #aae;}
</style>
</head>
<body>
<div>
<h3>CSS2.1 Attribute Selectors</h3>
<p valign="top"><p valign="top"> this should match p[valign]
and have a yellow background </p></p>
<p bgcolor="red"><p bgcolor="red"> this should match
p[bgcolor="red"] and have a purple background </p></p>
<p class="one two three"><p class="one two three"> this
should match p[class~="two"] and have a blue background </p></p>
<p lang="x-klingon"><p lang="x-klingon"> this should match
p[lang¦="x"] and have a grey background </p></p>
</div>
<div>
<h3>New to CSS3 Attribute Selectors</h3>
<p class="one-1"><p class="one-1"> this should match
p[class^="one"] and have a yellow background </p></p>
<p class="two-2"><p class="two-2"> this should match
p[class$="2"] and have a purple background </p></p>
<p class="three-3"><p class="three-3"> this should match
p[class*="ee"] and have a blue background </p></p>
</div>
<!--[if lt IE 7]>
<script src="http://ie7-js.googlecode.com/svn/version/2.0(beta3)/IE7.js"
type="text/javascript"></script>
<![endif]-->
</body>
</html>
Support:
Graceful fallback:
IE6 lack of support can be fixed by using IE7.js [code.google.com] making this usable if we want to.
Practical use:
Could be used to target older legacy code that still contains deprecated attributes e.g. <font color="red"> or it could be used to target only certain external link types so relevant icons can be added as background images e.g. a[href$=".pdf"] to add a PDF image link icon