≪ Today I learned. RSS購読
公開日
タグ
CSS
著者
ダーシノ(@bc_rikko)

min-widthとmax-widthが矛盾しているときのwidthの求め方

min-widthmax-widthが同時に設定されており、かつその値に矛盾が生じている場合がある。(CSSを掃除しない人がやりがち)

.box {
  /* minとmaxの値が逆転している */
  min-width: 600px;
  max-width: 300px;
}
  1. The tentative used width is calculated (without ‘min-width’ and ‘max-width’) following the rules under “Calculating widths and margins” above.
  2. If the tentative used width is greater than ‘max-width’, the rules above are applied again, but this time using the computed value of ‘max-width’ as the computed value for ‘width’.
  3. If the resulting width is smaller than ‘min-width’, the rules above are applied again, but this time using the value of ‘min-width’ as the computed value for ‘width’.

https://drafts.csswg.org/css2/#min-max-widths

  1. margin や width によって暫定的な幅(Tentative used width)が決まる
  2. その幅が max-width より大きい場合は width = max-width になる
  3. 2 までで決まった幅が min-width より小さい場合は width = min-width になる

つまり、min-widthの幅が有線される。

.box {
  min-width: 600px; /* 要素は600pxになる */
  max-width: 300px;
}

デモ

min-widthの値が優先される