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;
}
【参考サイト】
- table-layout: fixed; せずに text-overflow: ellipsis; する – コンパイラかく語りき
- table-layout – CSS: カスケーディングスタイルシート | MDN
コメントが承認されるまで時間がかかります。