Pages

Labels

Powered by Blogger.
Thursday, August 30, 2012

Child and adjacent sibling selectors


The first of these advanced selectors is the child selector. Whereas a descendant selector will select all the descendants of an element, a child selector only targets the element’s immediate descendants, or children. In the following example, the list items in the outer list will be given a custom icon while list items in the nested list will remain unaffected (see Figure 2-1):



#nav>li {
  background: url(folder.png) no-repeat left top;
  padding-left: 20px;
}

<ul id="nav">
  <li><a href="/home/">Home</a></li>
  <li><a href="/services/">Services</a>
    <ul>
      <li><a href="/services/design/">Design</a></li>
      <li><a href="/services/development/">Development</a></li>
      <li><a href="/services/consultancy/">Consultancy</a></li>
    </ul>
  </li>
  <li><a href="/contact/">Contact Us</a></li>
</ul>

The child selector styles the children of the list but not its grandchildren.

Figure 2-1. The child selector styles the children of the list but not its grandchildren.

The child selector is supported by IE 7 and above. However, there is a small bug in IE 7 that causes problems if there are HTML comments between the parent and child.

It is possible to fake a child selector that works in IE 6 and below by using the universal selector. To do this, you first apply to all of the descendants the style you want the children to have. You then use the universal selector to override these styles on the children’s descendants. So to fake the previous child selector example you would do this:

 #nav li {
  background: url(folder.png) no-repeat left top;
  badding-left: 20px;
}

#nav li * {
  background-image: none;
  padding-left: 0;
}

Sometimes, you may want to style an element based on its proximity to another element. The adjacent sibling selector allows you to target an element that is preceded by another element that shares the same parent. Using the sibling selector, you could make the first paragraph following a top-level heading bold, gray, and slightly larger than the subsequent paragraphs (see Figure 2-2):

h2 + p {
  font-size: 1.4em;
  font-weight: bold;
  color: #777;
}

<h2>Peru Celebrates Guinea Pig festival</h2>
  <p>The guinea pig festival in Peru is a one day event to celebrate
these cute local animals. The festival included a fashion show where
animals are dressed up in various amusing costumes.</p>
  <p>Guinea pigs can be fried, roasted, or served in a casserole. Around
65 million guinea pigs are eaten in Peru each year.</p>

The adjacent sibling selector can be used to style the first paragraph after a headline, allowing you to do away with extraneous classes.

Figure 2-2. The adjacent sibling selector can be used to style the first paragraph after a headline, allowing you to do away with extraneous classes.

As with the child selector, this fails in IE 7 if comments appear between the elements you are targeting.

0 Comments: