table内でtext-overflow ellipsisを使う

table内で文字省略をしたいことがあったので、table内での実装方法を試してみました。

サンプルコード

まずは文字省略設定前の状態を確かめてみます。

<table>
<tr>
<th>項目名</th>
<td>内容テキストテキストテキストテキストテキストテキストテキストテキストテキストテキストテキストテキストテキストテキストテキスト</td>
</tr>
<tr>
<th>項目名</th>
<td>内容テキストテキストテキストテキストテキストテキストテキストテキストテキストテキストテキストテキストテキストテキストテキスト</td>
</tr>
</table>

tableに幅指定のみ行います。

table {
	width: 80%;
}

対応前のデモページ

次に通常の文字省略を追加してみます。

table {
	width: 80%;
}
td {
	overflow: hidden;
	text-overflow: ellipsis;
	white-space: nowrap;
}

この記述のみだと文字省略されませんでした。
うまくいかなかった場合のデモページ

調べてみると、table-layout: fixed を指定することで実装できるという記事が多いようでした。

table {
	width: 80%;
	table-layout: fixed;
}
td {
	overflow: hidden;
	text-overflow: ellipsis;
	white-space: nowrap;
}

これで文字省略が実装できましたが、thとtdが同じ幅になってしまっています。
table-layout: fixedで対応した場合のデモページ

thもしくはtdに幅を指定することで調整します。

table {
	width: 80%;
	table-layout: fixed;
}
th {
	width: 20%;
}
td {
	overflow: hidden;
	text-overflow: ellipsis;
	white-space: nowrap;
}

これで概ね想定した形にできました。
table-layout: fixedで対応した場合のデモページ2

table-layout: fixed ではなく文字省略するtdに対してmax-width: 0 を指定する形でも実装できるようです。

table {
	width: 80%;
}
th {
	width: 20%;
}
td {
	overflow: hidden;
	text-overflow: ellipsis;
	white-space: nowrap;
	max-width: 0;
}

max-width: 0 で対応した場合のデモページ
 

【参考サイト】

 

このエントリーをはてなブックマークに追加

関連記事

コメントを残す

メールアドレスが公開されることはありません。
* が付いている欄は必須項目です

CAPTCHA


コメントが承認されるまで時間がかかります。

2024年3月
 12
3456789
10111213141516
17181920212223
24252627282930
31