child sibling selectors

Explanation: These CSS selectors (child and sibling) allows you to style elements which match a given condition. Although this capability has been around since CSS-2.1, it is enhanced in CSS-3. One needs to understand the DOM (Document Object Model) a bit, but if you identify which elements are direct children of a given element (and are siblings), one can style the document without relying a great deal on classes and identifiers.

In CSS-2.1 one could test for

  • children (if a given element is a direct child of a given element ( as in div > h2 ). In this case, we test to see if the h2 element is a direct child of the div element.
  • adjacent siblings (for sibling elements, the second must directly follow the first ( as in div + p). In this case, the p element must directly follow the div element and both must be siblings of another element.

In CSS-3 one can now also test for

  • sibling elements (but the second does not need to directly follow the first element ( as in div ~ p). In this case, as long as the p element is a sibling of the div element and both are siblings of another element, the style will be applied.

Example CSS code:

/* CSS-2 Specific styles */
div > h2 {
background-color: #900;
}

h2 + p {
background-color: #e00;
}

/* CSS-3 specific styles*/
h2 ~ p {
color: #999;
font-weight:bold;
}

Examine the linked document below and identify why certain rules apply.

Example page (view the source code): http://learning-html5.info/CSS3/CSS3_ChildSiblingSelector.html (should work in most modern browsers).

References:

Leave a Reply

Your email address will not be published. Required fields are marked *