Watkins Web 1

Part 4: Classes, IDs, Selectors

Classes vs. IDs

Classes and attributes should first be understood as attributes that you add to HTML entities – they just happen to be particularly useful as targets of CSS selectors. So you might change <p>Some content</p> to <p id="footer">Some content</p> so that you can style it a particular way.

The point of IDs is that they are unique identifiers for a particular HTML entity. Therefore, they only be used once on a page. If you want to create a set of things to be styled the same way, use a class: you could have <p class="infobox">Welcome to my site</p> near the top of the page and then <p class="infobox">Check out my other website...</p> further down the page.

CSS Selectors

Pay careful attention to the use of spaces: they indicate a descendent selector. p#special refers to the HTML element <p id="special">, but p #footer (with a space after the p) refers to “anything with an id of special inside a paragraph.” For example, the span inside <p>Some content <span id="special">some nested content<span></p>

This table summarizes the most common ways to style elements using IDs, classes, and descendent selectors:

What we want to style HTML CSS Rule
All paragraphs <p>Sample</p> p {color:red;}
All paragraphs with a class of special <p class="special">Sample</p> p.special {color:red;}
The (only) paragraph with an id of first <p id="first">Sample</p> p#first {color:red;}
Anything with a class of warning <p class="warning">Sample</p>, but also <ul class="warning">, <div class="warning">, etc., if they exist. .warning {color:red;}
Paragraphs nested inside the maincontent div <div id="maincontent"><p>Sample</p></div> div#maincontent p {color:red;}
List items nested inside unordered lists that have a class of ingredients <ul class="ingredients"><li>Sample</li></ul> ul.ingredients li {color:red;}