Dawid Zbiński Dawid Zbiński - 1 month ago 8
CSS Question

Disable automatic change of width in table tag

It's really simple. How can I do the table like this, but without automatic change of width in last column because of number "10" (2 ciphers)..

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="style.css" type="text/css">
<title>Tabuľka</title>
</head>
<body>
<table>
<tr>
<td class="center_bottom" rowspan="3">1</td>
<td class="right_bottom" id="red">2</td>
<td class="right_bottom">3</td>
<td class="right_bottom">4</td>
</tr>
<tr>
<td class="right_bottom">5</td>
<td class="center_bottom" id="blue"rowspan="2" colspan="2">7</td>
</tr>
<tr>
<td class="right_bottom" id="green">6</td>
</tr>
<tr>
<td class="right_bottom" id="yellow">8</td>
<td class="center_bottom"colspan="2">9</td>
<td class="right_bottom">10</td>
</tr>
</table>
</body>
</html>


and my css :

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

tr {
column-width: 100px;
}

td.right_bottom {
border: 1px solid;
text-align: right;
vertical-align: bottom;
}

td.center_bottom {
border: 1px solid;
text-align: center;
vertical-align: bottom;
}

#red {
background-color: red;
}

#green {
background-color: green;
}

#blue {
background-color: blue;
}

#yellow {
background-color: yellow;
}

Answer

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/

Comments