Dawid Zbiński
Dawid Zbiński

Reputation: 5826

Disable changing of width in html table

I'm trying to create a "fixed-width" table, but it somehow changes the column width whenever the data in column is bigger than rest of them.

For example, following table changes the width on the last number, which is 10.

<table>
    <tr>
        <td rowspan="3">1</td>
        <td>2</td>
        <td>3</td>
        <td>4</td>
    </tr>
    <tr>
        <td>5</td>
        <td rowspan="2" colspan="2">7</td>
    </tr>
    <tr>
        <td>6</td>
    </tr>
    <tr>
        <td>8</td>
        <td colspan="2">9</td> 
        <td>10</td>
    </tr>
</table>

Here's my CSS:

table {
    border: 1px solid;
    width: 400px;
    height: 300px;
}

Upvotes: 5

Views: 19913

Answers (2)

FelipeAls
FelipeAls

Reputation: 22181

There are 2 algorithms for tables in CSS, triggered by the property table-layout:

  • table-layout:fixed will adapt cell widths to what the author (you) want, as far as possible
  • table-layout:auto (default value) will adapt cell widths to their content.

CSS

  table {
    table-layout: fixed;
    width: 400px;
    height: 300px;
    border: 1px solid;
  }

Here's a fiddle: http://jsfiddle.net/tk4J8/

Upvotes: 13

Phire
Phire

Reputation: 398

Don't use column-width to specify width of table columns - it's a suggested optimal guideline for browsers that isn't really meant for fixed width layouts. Use colgroups instead.

Remove the column-width style in your stylesheet, and add this to your table tag before any tr or td tags:

<colgroup>
    <col span="1"></col>
    <col span="1"></col>
    <col span="1"></col>
    <col span="1"></col>
</colgroup>

And add this to your stylesheet:

colgroup col {
    width: 100px;
}

jsFiddle.

Here's the Mozilla documentation for it.

Upvotes: 0

Related Questions