CSS Selectors
Last update on: 06-23-2008Any tag can serve as a CSS selector, and the rules for that selector will be applied to all instances of that tag on the page. You can add a rule to the b tag that sets the font weight to normal if you choose to do so, or italicize every paragraph on your page by applying a style to the p tag. Applying styles to the <body> tag using the body selector enables you to apply page wide settings. However, there are also a number of ways to apply styles on a more granular basis and to apply them across multiple types of elements using a single selector.
Let's take for example you want all unordered lists, ordered lists, and paragraphs on a page to be displayed using blue text. Rather than writing individual rules for each of these elements, you can write a single rule that applies to all of them. Here's the syntax:
p, ol, ul { color: blue }
p { color: blue }
ol { color: blue }
ul { color: blue }
Contextual Selectors:
These are used to apply styles to elements only when they're nested within other specified elements. Here is an example:
p ol { color: blue }
p cite { font-style: italic; font-weight: normal }
li cite { font-style: normal; font-weight: bold }
cite { color: green }
p cite { font-style: italic; font-weight: normal }
li cite { font-style: normal; font-weight: bold }
Classes and IDs:
Sometimes selecting by tag (even using contextual selectors) isn't specific enough for your needs, and you must create your own classifications for use with CSS. There are two attributes supported by all HTML tags: class and id. The class attribute is for assigning elements to groups of tags, and the id attribute is for assigning identifiers to specific elements.To differentiate between classes and regular element names in your rules, you prepend . to the class name. So, if you have a tag like this:
<div class="important">Some text.</div> <p class="important">your paragraph here.</p>
.important { color: red; font-weight: bold; }
div.important { color: red; font-weight: bold; }
p.important { color: blue; font-weight: bold; }
.important { font-weight: bold; }
div.important { color: red; }
p.important { color: blue; }
Whenever you want to specify styles for one element in a style sheet, assign it an ID. Assigning IDs to elements is also very useful when using JavaScript or dynamic HTML because doing so lets you write programs that reference individual items specifically. For now, though, let's look at how IDs are used with CSS. Generally, a page will have only one footer. To identify it, use the id attribute:
<div id="footer"> Copyright 2008, Company Inc. </div>
#footer { font-size: small; }
h1, #headline, .heading, div.important { font-size: large; color: green; }
ul li.sample2 { color: red }
Layouts with CSS's lessons:
Adding CSS To PagesCSS Selectors
Units Of Measure
Box Properties

