Thursday, May 5, 2011

CSS Nested not working the way i want it to!

Well lets say i have this

<table class="infoBox">
    <tr>
        <td>
            test
        </td>
        <td>
            <table>
                <tr>
                    <td>
                        this should not be bold!
                    </td>
                </tr>
            </table>
        </td>
    </tr>
</table>

And then we got some css for this

Table.infoBox tr td { font-weight: bold; }

now my problem is that the nested table seems to get the css also when i only want the outer table to get this css how do i define it in a way so that nested tables are not affected by the css?

From stackoverflow
  • While you could do this with immediate child, this isn't supported by all browsers. Try:

    table.infoBox tr td { font-weight: bold; }
    
    table.infoBox table tr td { font-weight: normal; }
    

    All that the selector table.infoBox tr td says is:

    Apply this style to any <td> tag which is a child of any <tr> tag, which is a child of any table with a class of infoBox.

    Therefore, you need to get more specific below this style block in order to declare what you want to do for tables within tables of class infoBox.

  • Either use the child selector:

    table.infoBox > tbody > tr > td { font-weight: bold; }
    

    (not supported in IE6)

    Note: the mysterious tbody element. This is inserted by the browser if you don't put it in. That's because tables have three sections: thead, tbody and tfoot.In the absence of one of those, rows are added to the tbody element.

    or a combination:

    table.infoBox tr td { font-weight: bold; }
    table.infoBox tr td td { font-weight: normal; }
    

    There are many potential variations of this one.

  • Table.infoBox table tr td { font-weight: normal; }

  • It may also suffice to use:

    table.infoBox { font-weight: bold; }
    table.infoBox table { font-weight: normal; }
    

    or

    table.infoBox tr { font-weight: bold; }
    table.infoBox table tr { font-weight: normal; }
    

    Though all css depends on other font-weight rules throughout your css, it's handy to note that css declerations are based on decendensy, not direct parent child relation ship. So table{} will have just the same effect on the content as td{} so long as you don't have anything stronger or closer to the content defined.

0 comments:

Post a Comment