CSS Selector Tricks Beyond the Basics
Attribute selectors and pseudo-elements can do far more than typical styling tasks. For example, empty links become easy to spot with a selector targeting a[href=""], and absolute URLs can be styled separately from relative ones using a substring match like a[href^="http"].
a[href = ""] {
background: red;
color: white;
font-size: x-large;
}
a[href ^= http] {
display: inline-block;
color: red;
transform: rotate(180deg);
}
For off-site links, pairing the :not() selector with a prefix match keeps the styling internal—this technique powers the external-link arrows seen on HTML5Rocks. Image inversion is equally straightforward: applying a CSS filter to a simple img[src$=".png"] rule flips all PNGs.
a[href ^= 'http']:not([href *= 'html5rocks.']) {
background: transparent url(arrow.png) no-repeat center right;
padding-right: 16px;
}
img[src $= .png] {
filter: invert(100%);
}
Selectors also unlock structural tricks. Making the document head (and its children) visible is possible, and the attr() function can pull attribute values from a matching element to populate ::before and ::after content—so #foo::before reads attributes directly from #foo.
head {
display: block;
border-bottom: 5px solid red;
}
script, style, link {
display: block;
white-space: pre;
font-family: monospace;
}
script:before {
content: "<script src=\"" attr(src) "\" type=\"" attr(type) "\">";
}
script:after {
content: "</script>";
}
style:before {
content: "<style type=\"" attr(type) "\">";
}
style:after {
content: "< /style>";
}
/* And for a finish, <link> */
link:before {
content: "<link rel=\"" attr(rel) "\" type=\"" attr(type) "\" href=\"" attr(href) "\" />";
}
Live demos for these snippets are available on jsFiddle: empty links, absolute vs. relative, external links, and attr() content.



