In the usual blog-style, a handy “Top x” list for the most commonly used (well, my most commonly used anyway) CSS selectors, giving you a useful CSS cheat sheet to save you time and hassle in developing your styles.
- “*” - Any Element. Matches any element. Great for setting global font parameters. Example:
* { font-family: Arial; } - “element” - Specified Element. If you only care about styling a particular element, such as a <blockquote>, or a <p> this is the selector for you. Example:
blockquote { border: 1px solid #FF0000; } - “Parent > Child” - Match any element that is a child of Parent. If you want a different style for elements that are nested within a particular element, you can use this selector. For example, if you wanted all links that were in an unordered list to not be underlined:
ul > a { text-decoration: none; } - “Ancestor Descendant” - Match any element that is a Descendant of the Ancestor. Very similar to a Child, a Descendant is an element that is a descendant of some ancestor element. Take the real-life example of a Grandparent - although you are not one of your Grandparent’s children (that is one of your parents), you are one of their descendants.For example, if you wanted all <a> descendants of the “smith” <div> class to be blue irrespective of any subsequent nesting, you could use this
div.smith a { color: blue; } - “First + Second” - Match any element that comes after the First (adjacent siblings). This selector allows you to match only elements that come after some other element and who have the same parent. For example, if you wanted to use a <p> directly after an <img> to give the image a caption, you could use:
img + p { font-style: italic; } - “#Identifier” - Match any element that has an ID attribute equal to “Identifier”. Often used with <divs> to style layouts, the ID allows you to style a unique part of your design. For example, if you had a <div> with an ID attribute of “main” that was going to contain most of your site’s main content, you could style it using:
#main { width: 760px; border: 1px solid #000000; }
So there you go, my top 6 CSS selectors. For more information, and formal definitions of each selector type, please have a look at the W3 CSS2 Selectors document.