How to correctly set the column widths on my HTML table?
Tags: html,css
Problem :
This may sound like a basic question. I know how to set column widths by using the width tag. And by using CSS.
Take this HTML:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta content="en-gb" http-equiv="Content-Language">
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
<title>Untitled 1</title>
<style type="text/css">
.tableStyle {
border-collapse: collapse;
border: 1px solid #000000;
}
</style>
</head>
<body>
<table class="tableStyle" style="width: 100%">
<tr>
<td>This is long text</td>
<td>Date Column</td>
<td>Date Column</td>
</tr>
<tr>
<td>This is long text</td>
<td>Date Column</td>
<td>Date Column</td>
</tr>
<tr>
<td>This is long text</td>
<td>Date Column</td>
<td>Date Column</td>
</tr>
<tr>
<td>This is long text</td>
<td>Date Column</td>
<td>Date Column</td>
</tr>
</table>
</body>
</html>
If possible, what I would like to do is set columns 2 and 3 to the size needed to show the content for those columns. And for column 1 to expand to fit.
Now, I know I can set the last 2 columns to, let us say, 10% each. And if I set the table width to 100% then column 1 will expand to fit.
But, since this HTML template will be used for over 30 languages, the column headings have more characters in some languages. In addition, if the font size is changed it would also throw it out.
So is there any way to get the last 2 columns to auto-size to content and first column expand to fit?
Thank you.
Andrew
Solution :
Use the <col>
tag, which represents each column in the table, and style that. Here are two different ways to do what you want:
- Set the width of the first column to 100%
table {
width: 100%;
}
<table border="1">
<col style="width: 100%">
<col>
<col>
<tr>
<td>This is long text</td>
<td>Date Column</td>
<td>Date Column</td>
</tr>
<tr>
<td>This is long text</td>
<td>Date Column</td>
<td>Date Column</td>
</tr>
<tr>
<td>This is long text</td>
<td>Date Column</td>
<td>Date Column</td>
</tr>
<tr>
<td>This is long text</td>
<td>Date Column</td>
<td>Date Column</td>
</tr>
</table>
- Set the widths of the two other columns
table {
width: 100%;
}
<table border="1">
<col>
<col style="width: 11%">
<col style="width: 11%">
<tr>
<td>This is long text</td>
<td>Date Column</td>
<td>Date Column</td>
</tr>
<tr>
<td>This is long text</td>
<td>Date Column</td>
<td>Date Column</td>
</tr>
<tr>
<td>This is long text</td>
<td>Date Column</td>
<td>Date Column</td>
</tr>
<tr>
<td>This is long text</td>
<td>Date Column</td>
<td>Date Column</td>
</tr>
</table>