table内でtext-overflow ellipsisを使う

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

サンプルコード

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

1
2
3
4
5
6
7
8
9
10
<table>
<tr>
<th>項目名</th>
<td>内容テキストテキストテキストテキストテキストテキストテキストテキストテキストテキストテキストテキストテキストテキストテキスト</td>
</tr>
<tr>
<th>項目名</th>
<td>内容テキストテキストテキストテキストテキストテキストテキストテキストテキストテキストテキストテキストテキストテキストテキスト</td>
</tr>
</table>

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

1
2
3
table {
    width: 80%;
}

対応前のデモページ

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

1
2
3
4
5
6
7
8
table {
    width: 80%;
}
td {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

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

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

1
2
3
4
5
6
7
8
9
table {
    width: 80%;
    table-layout: fixed;
}
td {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

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

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

1
2
3
4
5
6
7
8
9
10
11
12
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 を指定する形でも実装できるようです。

1
2
3
4
5
6
7
8
9
10
11
12
table {
    width: 80%;
}
th {
    width: 20%;
}
td {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    max-width: 0;
}

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

【参考サイト】

 

関連記事

コメントを残す

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

CAPTCHA


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

2025年3月
 1
2345678
9101112131415
16171819202122
23242526272829
3031