That's known as the attribute-starts-with selector, available in CSS3. It matches links with href
attributes whose values start with the given string.
To illustrate, we'll take your example CSS, and add some defaults:
a {
background: none; padding: 0 1em;
}
a[href^="http:"] {
background: url(img/keys.gif) no-repeat right top;
}
a[href^="http://mysite.com"], a[href^="http://www.mysite.com"] {
background-image: none; padding-right:0;
}
And style the following HTML with it. The output styles are summarized in comments:
<ul>
<!-- [1] No background, 1em left and right padding -->
<li><a href="/index.php">My site's page</a></li>
<!-- [2] Background, 1em left and right padding -->
<li><a href="http://example.com">External link</a></li>
<!-- [3] No background, no right padding -->
<li><a href="http://mysite.com">My site's base URL without www</a></li>
<!-- [4] No background, no right padding -->
<li><a href="http://www.mysite.com">My site's base URL with www</a></li>
<!-- [5] No background, no right padding -->
<li><a href="http://mysite.com/page.php">A page in my site with base URL</a></li>
</ul>
What's happening?
Matched only by a
Its href="/index.php"
attribute doesn't start with http:
or the other values.
There is no background, but there is left and right padding.
Matched only by a[href^="http:"]
Its href="http://example.com"
attribute starts with http:
but doesn't start with http://mysite.com
.
There is both left and right padding, and a background image.
Matched by a[href^="http:"]
and a[href^="http://mysite.com"]
Its href="http://mysite.com"
attribute starts with http:
and further starts with http://mysite.com
.
Since the second selector overrules the first selector, the background image and right padding are removed.
Matched by a[href^="http:"]
and a[href^="http://www.mysite.com"]
Its href="http://www.mysite.com"
attribute starts with http:
and further starts with http://www.mysite.com
(notice the www).
Since the second selector overrules the first selector, the background image and right padding are removed.
Matched by a[href^="http:"]
and a[href^="http://mysite.com"]
Its href="http://mysite.com/page.php"
attribute starts with http:
and further starts with http://mysite.com
.
Notice that, compared to the third link, the attribute in this one contains more than just the base URL; however, the ^=
indicates that the attribute's value just needs to start with your site's base URL, as opposed to =
which would mean "select links that only point to http://mysite.com
". Therefore, this link is matched by the second selector.
Since the second selector overrules the first selector, the background image and right padding are removed.