小池啓仁 ヒロヒト応援ブログ By はてな

小池啓仁(コイケヒロヒト)の動画など。

小池啓仁 ヒロヒト応援ブログ By はてな

HTMLテーブルのセル幅を制御するパート1

詳解HTML & XHTML & CSS辞典
HTMLテーブルのセル幅の制御方法には、大きく分けて『auto』と『fixed』の2つのモードがあります。
モードは、CSSのtable-layoutプロパティで『auto』か『fixed』を指定します。
『auto』は、セル幅をブラウザが自動的にレンダリングしてくれます。
『fixed』は、セル幅をth要素やcol要素のwidth属性で指定します。


列数が多い(たとえば20以上)場合、『auto』にすると、th要素やcol要素のwidth属性をいくら指定しても無効になります。
列数が少ない場合は、変な割合でwidthが効きます。
つぎに、『fixed』にするとwidthは、列数に関係なく有効になりますが、長いスペルの英語(半角文字)がセル内にすべて表示されない場合があります。


では、widthが列数に関係なく有効で、長いスペルの英語(半角文字)がすべて表示されるようにするには、どうしたらよいでしょうか?


この場合は、th要素にnowrap属性を指定します。


なぜか上手く行くのです。
あたかも、『auto』と『fixed』の折衷モードみたいになるのです。
しかし、IE系だけかも(実際、Firefoxの『auto』では、nowrapしてもwidthが効かない)。

サンプル

<html>
<body>
<table border="1" style="table-layout: auto">
<col span="1" width="50px">
<col span="1" width="60px">
<col span="1" width="70px">
<col span="1" width="80px">
<col span="1" width="90px">
<col span="1" width="50px">
<col span="1" width="60px">
<col span="1" width="70px">
<col span="1" width="80px">
<col span="1" width="90px">
<caption>サンプル</caption>
<thead>
<tr>
<th nowrap>見出し1</th>
<th nowrap>見出し2</th>
<th nowrap>見出し3</th>
<th nowrap>見出し4</th>
<th nowrap>見出し5</th>
<th nowrap>見出し6</th>
<th nowrap>見出し7</th>
<th nowrap>見出し8</th>
<th nowrap>見出し9</th>
<th nowrap>見出し10</th>
</tr>
</thead>
<tbody>
<tr>
<td>aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa</td>
<td>データ2</td>
<td>データ3</td>
<td>データ4</td>
<td>データ5</td>
<td>データ6</td>
<td>データ7</td>
<td>データ8</td>
<td>データ9</td>
<td>データ10</td>
</tr>
</tbody>
</table>
</body>
</html>