AlexStack AlexStack - 3 months ago 14
CSS Question

Equal cell width after multiple columns are removed

Update: here is a follow up question with colspans.

I have a table with 8 columns. At runtime, any number of these elements are removed.

The remaining columns would have equal width. The problem is when the text inside the elements has difference width. Because it seems the browser sets the cell widths based on the length of the text inside each cell. OK, this image probably says it better:

enter image description here

And here is the code:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<style type="text/css">
table{
width:600px;
}
table td{
border:1px solid red;
text-align:center;
background-color:#FFFFCC;
}
caption{
color:blue;
font-size:80%;
}
</style>
<title></title>
</head>
<body>
<table>
<caption>Original table</caption>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
<td>6</td>
<td>7</td>
<td>8</td>
<tr>
</table>
<table>
<caption>After some columns are removed</caption>
<tr>
<td>1</td>
<td>2</td>
<td>4</td>
<td>5</td>
<td>7</td>
<td>8</td>
<tr>
</table>
<table>
<caption>I want these to have the same width</caption>
<tr>
<td>1</td>
<td>Two</td>
<td>Three</td>
<td>Column number four</td>
<td>5</td>
<tr>
</table>
<table>
<caption>I want these to have the same width, too</caption>
<tr>
<td>1</td>
<td>Column number four</td>
<td>5</td>
<tr>
</table>
</body>
</html>


I searched stackoverflow and found the following posts but they are not my answer:


Answer

You can use table-layout:fixed on the table to stop the browser auto resizing the table depending on its contents. Then you will have to give each TD a set width. Any TDs without a set width will take up the remaining width.