Html – CSS & Overriding Styles on Nested Elements

csshtmlstyles

This came up from another question that was asked here but I figure it's something that probably has a "Best Practice" Approach.

When designing a website, the designer will most likely put together a set of generic styles for all elements within a website. (Standard Fonts for Text in Divs/Spans/H1/H2s)

In the case of tables, they may be defining default sitewide borders and alignments as well… e.g.

Table
{
   border: dashed 1px #333333;
   padding: 2px;
}

However if you have a table within a table (from RSolberg's example, an AJAX Calender within a DataGrid) then both your parent & nested tables will both inherit these styles. (Suppose that's why they're called Cascading)

My question is what's the best practice for applying styles to top most elements without having sub-elements also inherit them.

Should you just provide an override which undoes whatever styling you've applied.

e.g.

Table
{
   border: dashed 1px #333333;
   padding: 2px;
}

Table Table
{
   border: solid 0px #000000;
   padding: 0px;
}

Best Solution

If you have HTML like this:


<html>
  ...
  <body>
    <div>
      <div>
      <div>
    <div>
  </body>
</html>

You could apply styles only to the div that is child of the body element using the child selector (>) like this:

body > div
{
  border:solid 1px orange;
}

The nested div will not get a border.

For more information please visit: http://www.w3.org/TR/CSS2/selector.html#child-selectors.

Please note that Internet Explorer 6 does not support the child selector.