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