Alex Rivera | Logout

CSS & Overriding Styles on Nested Elements

Asked 2009-04-21T18:25:28.070
14

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;
}
Edit
Report

1 Answer

5

Yes. The "table table" rule will override the "table" rule because it's more specific. What you described is the best way to have one style for the outermost table and another style for inner tables -- assuming neither table has a class or ID that would allow you to use more semantic selectors.

In practice, you're more likely to need to use this technique with lists.

ol { list-style: upper-roman }
ol ol { list-style: upper-alpha }
ol ol ol { list-style: lower-roman }
ol ol ol ol { list-style: lower-alpha }
answered 2009-04-21T18:30:48.043

Your Answer