CSS Selectors you Must Memorize
Posted on July 19, 2011 | Comments Off on CSS Selectors you Must Memorize
The star symbol will target every single element on the page. Many developers will use this trick to zero out the margins and padding. While this is certainly fine for quick tests, I’d advise you to never use this in production code. It adds too much weight on the browser, and is unnecessary.
* { margin: 0; padding: 0; }
Compatibility | IE6+ | Firefox | Chrome | Safari | Opera
The next most comment selector is the descendant selector. When you need to be more specific with your selectors, you use these. For example, what if, rather than targeting all anchor tags, you only need to target the anchors which are within an unordered list? This is specifically when you’d use a descendant selector.
li a { text-decoration: none; }
Compatibility | IE6+ | Firefox | Chrome | Safari | Opera
This is referred to as an adjacent selector. It will select only the element that is immediately preceded by the former element. In this case, only the first paragraph after each ul will have red text.
ul + p { color: red; }
Compatibility | IE7+ | Firefox | Chrome | Safari | Opera
The difference between the standard X Y and X > Y is that the latter will only select direct children. For example, consider the following markup.
div#container > ul { border: 1px solid black; }
A selector of #container > ul will only target the uls which are direct children of the div with an id of container. It will not target, for instance, the ul that is a child of the first li.
Compatibility | IE7+ | Firefox | Chrome | Safari | Opera
Referred to as an attributes selector, in our example above, this will only select the anchor tags that have a title attribute. Anchor tags which do not will not receive this particular styling. But, what if you need to be more specific?
a[title] { color: green; }
Compatibility | IE7+ | Firefox | Chrome | Safari | Opera
Again, we use a regular expressions symbol, $, to refer to the end of a string. In this case, we’re searching for all anchors which link to an image — or at least a url that ends with .jpg. Keep in mind that this certainly won’t work for gifs and pngs.
a[href$=".jpg"] { color: red; }
Compatibility | IE7+ | Firefox | Chrome | Safari | Opera
Hope it was good, there are lot to bring but those are not much compatible with IE7, so lets wait 🙂