Monday, October 5, 2009

Basic CSS (Cont.)

Descendant Selectors
Descendant selectors, sometimes called contextual selectors, allow you to create style rules that are effective only when an element is the descendant of another one. Descendant selectors are indicated by a space between two elements. As an example, you may want to style only li elements that are descendants of ul lists (as opposed, say, to those who are part of ol lists). You’d do so like this:
ul li {
          color: blue;

}
This rule will make li text blue—but only when the li is contained within a ul element. So, in the following code, all li elements would be blue:
 <ul>
   <li>Item one</li>
   <li>Item two</li>
   <li>Item three</li>
   <li>Item four has a nested list
     <ol>
       <li>Sub-item one</li>
       <li>Sub-item two</li>
     </ol>
  </li>

</ul>
Even though the nested list in item four is an ol element, the blue color will still be
applied to its list items because they are the descendants of a ul. Descendant selectors can be useful in targeting items deep in your (X)HTML structure, even when they don’t have an ID or class assigned to them. By stringing together many elements, you can target strong elements inside cite elements inside blockquote elements inside div elements:
div blockquote cite strong {
  color: orange;
}

You can combine these with your class and ID selectors to get even more specific. Perhaps we want only li elements in ul elements with a class of ingredients inside our div with the id value recipes:
div#recipes ul.ingredients li {
  font-size 10px;
}

As you can imagine, descendant selectors are powerful, and it’s no coincidence that descendant selectors are among the most-used types of CSS selectors.

No comments:

Post a Comment