CSS Selectors
Cascading Style Sheets (CSS) are used to style html documents. A CSS statement has two parts: a selector, which specifies the part of the document, and declarations, which describes the formatting to apply. A typical piece of CSS looks like this:
The key to CSS is understanding how selectors work. The table summarises the main selectors in CSS 2.1.
Selector | Example | Explanation |
---|---|---|
Type | li { color: blue; } |
Matches all the li elements. |
Class | .intro { color: red; } |
Matches all elements with the intro class attribute. |
ID | #nav { color: blue; } |
Matches the single element with the id nav . |
Descendent | div p { colour: green; } |
Matches all elements p which are contained within a div . The p does not have to be a direct descendent. |
Universal | * { margin: 0; padding: 0; } |
Matches all elements. |
Child | div > em { color: blue; } |
Matches all em which are a direct descendent of a div . (Not IE6) |
Adjacent | h1 + h3 { margin: -20px; } |
Matches h3 which immediately follow an h1 . (Not IE6) |
Attribute | img[src] { margin: 0; } |
Matches all img elements whose src attribute is set. (Not IE6) |
Attribute | img[src="small.gif"] { margin: 0; } |
Matches all img elements which contain an attribute src="small.gif" . (Not IE6) |
Pseudo | p:first-letter { font-weight: bold; } |
Style information not available in the document tree.:first-letter :first-line :first-child :link :visited :hover :active :focus Not IE6: :before :after
|
An ID can only be used once within a document, whereas a class can be used multiple times. In the style sheet the ID selector has greater weight than class selector. ID's are generally used to identify the top level containers on the page, classes are then used to identify the lower level containers. ASP.NET has a problem with ID's, it tends to mangle the id attribute for elements with runat="server"
. For these elements you have to stick with the class attribute, which ASP.NET leaves alone.
Selectors can be grouped as a comma-separated list, if they share the same declaration block. For example:
With grouped decent selectors, you need to be careful that you repeat the whole decent. For example #sidebar h2, h3
will select the h2
elements in the sidebar, plus the h3
elements in the whole document.
I'm embarrassed to admit that I learnt my basic CSS from Sams Teach Yourself CSS in 10 Minutes by Russ Weakly. But hey, honesty is the best course, and its actually an OK book.