Search code examples
htmlcsscolorsbackgroundcss-tables

CSS Set Table Cell Background Color Using Text Inside Table Cell


Have basically the same problem as Possible to fill a table cell with a bg color? - text has a background color set and is in a table cell. Text background color is only behind the text, and does not fill the entire table cell, which it should.

The solution is normally to set a bgcolor on the table cell. Difference is that this occurs in many places throughout this particular website, and changing all the relevant table cells would take a very long time.

Question is, is there a way to say in CSS, either of:

  1. Make the text background colour fill the whole table cell (if the text is in a table cell); or.....
  2. If a table cell contains a text element which has style x, then make that table cell have a background colour (a kind of reverse inheritance)?

PS: the site was developed for IE6 originally, and IE6 already fills the entire table cell with the text's background color, so initially no issues. FF and IE 7+ work differently though.


Solution

  • As David Dorward said, there's no way to do exactly what you want cleanly with CSS, however I can think of a few workarounds...

    Assuming your html is something like this (i.e. the thing with the background color is the only thing in the table cell):

    <table>
        <tr>
            <td>test with longish string<br/> over two lines<td>
            <td><span class="bg" >test</span></td>
        </tr>
        <tr>
            <td>test with longish string<br/> over two lines<td>
            <td>test with longish string<br/> over two lines<td>
        </tr>
    </table>
    

    You could do this to your CSS:

    td { height: 100%;}
    .bg { background-color: #f00; width: 100%; height: 100%; display: block; }
    

    It works in this simple example (at least in firefox 3.5), but could have other side effects depending on what the content of your html looks like.


    Edit: Another option if you're ok with hacking it via javascript, is to use jQuery like this:

    $(function() { $("td:has(span.bg)").addClass("bg"); });
    

    This works on the above example html/css, but would obviously need to be changed to match your css classes, etc.