Disable changing of width in html table
Asked Answered
L

2

5

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;
}
Liberec answered 9/1, 2014 at 23:34 Comment(0)
L
13

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/

Lamprey answered 9/1, 2014 at 23:44 Comment(0)
E
0

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.

Eratosthenes answered 9/1, 2014 at 23:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.