Search code examples
csshtmlhtml-tablecss-tablescolumn-width

<td style="width"> attribute works inline but not in external stylesheet


I'm trying to use external css to format a 3-column table with 100% width and column widths of 10%, 80%, and 10% respectively. All my td attributes work from the external stylesheet except width.

<td style="width:10%">

works in inline css, but not as an internal style or from the external stylesheet. It will read td widths from the external css if I remove the 100% width attribute from the table, but then the width of my table changes depending on the amount of text in it. I have tried using

table-layout: fixed;

with no success. I've also tried removing width from one column at a time with no effect. All the examples I can find use pixels instead of % widths.

Have I missed something simple about table design?

Here's the relevant part of my external css:

table.border td {
    border-width: 5px;
    padding: 10px;
    border-style: ridge;
    border-color: white;
    border-collapse: collapse;
    -moz-border-radius: 0px 0px 0px 0px;
    vertical-align: top;
    width: 100%;
}

 td.edge {
    background-color: green;
    width: 10%;
}
  td.center{
    width: 80%;
    background-color: pink;
}

and here's the table's html:

<table class="border" >
<tr>
<td class="edge"> hi there</td>
<td class="center">it's me</td>
<td class="edge"> bye there</td>
</tr>
</table>

The table it gives me has a wide first column and narrow second and third columns.


Solution

  • Correct the CSS as follows (just removing "td" from this line: "table.border td") and it will work as expected:

    table.border{
        border-width: 5px;
        padding: 10px;
        border-style: ridge;
        border-color: white;
        border-collapse: collapse;
        -moz-border-radius: 0px 0px 0px 0px;
        vertical-align: top;
        width: 100%;
    }
    
     td.edge {
        background-color: green;
        width: 10%;
    }
      td.center{
        width: 80%;
        background-color: pink;
    }
    

    This is jsfiddle example: https://jsfiddle.net/r281bv1z/

    Hope this may help.