28
34

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

複雑な(説明|定義)リストdl,dt,ddの見た目を表のようにするCSS

Last updated at Posted at 2016-07-25

概要

dtddが1:1対応でdtの方が中身が長かったり,ddの方が中身が長かったりする(説明|定義)リストの見た目を表のようにするCSSの書き方
いろいろ試行錯誤の末,1つの答えを見つけたのでまとめる

今回は特に下記のように,表の左側に背景色をつける場合

つまり

html
<dl>
    <dt>short-short</dt>
    <dd>short-short-short</dd>
    <dt>middle-middle-middle-middle-middle-middle-middle</dt>
    <dd>long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long</dd>
    <dt>long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long</dt>
    <dd>short</dd>
    <dt>middle-middle-middle-middle-middle</dt>
    <dd>long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long</dd>
    <dt>middle-middle-middle-middle-middle-middle-middle</dt>
    <dd>long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long</dd>
    <dt>long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long-long</dt>
    <dd>short</dd>
</dl>

のような(説明|定義)リストを

dl-table.png

のようにする

結論

css
dl,
dt,
dd {
  box-sizing: border-box;
}
dl {
  background: #eee;
  border-right: 1px solid #ccc;
  border-bottom: 1px solid #ccc;
  border-left: 1px solid #ccc;
}
dt,
dd {
  padding: 10px 10px 0 10px;
  border-top: 1px solid #ccc;
}
dt {
  width: 40%;
  float: left;
}
dd {
  background: #fff;
  margin-left: 40%;
  padding-bottom: 10px;
  border-left: 1px solid #ccc;
}
dd:after {
  content: '';
  display: block;
  clear: both;
}

TIPS

  • dtにはfloat: left;付けるが,ddには付けない
  • dtの幅と同じだけddの左マージンをあける
  • ddの後(擬似要素after)で回り込みを解除する(float: left;)
  • 表内部のpaddingの内,padding-bottomddにのみ付ける
  • 表の左側の背景色で背景色で表全体を塗った上で,右側(dd)の背景色を全体の背景色と同じにする

1つ残念な点としては,本来,背景色をつけない方の背景色を背景と同じ色にしなくてはならないということ.
ただ,表の右半分にのみ背景色を付けたい場合はこの分ではないし,リクワイアメントは達成できていると思う.

28
34
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
28
34

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?