CSS Selectors, the Hacks

News Feed

The wild card, and holly hack

For some painful reason not every browser supports css is quite the same way and some method is needed to be able to pick them out. One well know example is called the holly hack. It uses the CSS selector * which is a wild card and can be used to select anything.

* {
padding : 2px ;
}
p * {
font-weight : bold ;
}
p * a {
font-weight : bold ;
}
* html a {
display : none ;
}

The first example here will give every thing a padding of 2px. The second example will make any element inside a paragraph bold. The third example can be best thought of as selecting the grand-child of the paragraph tag, if it is a link.

It is the final example that we call the holly hack. The * selects links that are in the HTML element but only if the HTML element has something above it. Anyone that has written HTML should know that should never be the case, but in IE 6 and below it is. IE 7 finally got it right. So when you need to target IE this is one method.

Missing IE 6

It is also possible to write rules that IE 6 and below will not see by using direct child selector.

html > body .ie-is-bad {
display : none ;
}

The body element is always directly inside the HTML element. But since IE 6 does not understand the > so it is ignored. All other browsers should hide anything with a class of ie-is-bad. Following is a few more selectors that are not supported in IE 6 but other browser such as IE 7, Firefox and Opera can understand.

/* the first paragraph after a h2 heading is bold */
h2 + p {
font-weight : bold ;
}
/* red border for all images with alt text */
img[alt] {
border : 1px solid red ;
}
/* all inputs tags with type="text" have a 2px thick gray border */
input[type="text"] {
border : 2px solid gray ;
}
/* both of these are the same, they select an element if its attribute contains something. In the first the values are space-separated the second hyphen-separated */
a[rel~="my-site friend-site"] {
color : red ;
}
a[rel|="nofollow-external"] {
color : red ;
}
/* this would select something from the shop sub-domain */
a[href^="http://shop."] {
color : green ;
}
/* highlight all links to GIF images */
a[href$=".gif"] {
background : yellow ;
}
/* a link that points to the site example.com */
a[href*="example.com"] {
font-weight : bold ;
}