LoginSignup
1
1

More than 5 years have passed since last update.

width,heighとpaddingの同時指定によるレイアウト崩れをbox-sizingdで防ぐ

Last updated at Posted at 2016-03-27

htmlを書き始めのときに、widthとpaddingを同時に使うとレイアウトが思い道理にいかないことがよくあった。
CSS3でbox-sizingというプロパティがあることを知り、簡単な例を作ったのでメモ。

box-sizingプロパティ

box-sizingはボックスサイズの算出法を指定する.
以下の値を取れる。


content-box

パディングとボーダーの高さと幅を含めない(デフォルト値)

border-box

パディングとボーダーの高さと幅を含める

inherit

親要素を継承

border-boxを指定することでレイアウト崩れを防ぐことができる。

box-sizingの例
例では上から2つ目の緑色のブロックでborder-boxを指定した。
paddingとborderプロパティの値を指定しているが、オレンジのブロックを同じサイズでボックスサイズに影響を受けていない。
上から3,4つ目の青色のブロックにはcontent-boxを指定した。
paddingとborderの影響を受けてボックスサイズがずれてしまう。

box-sizingの例
<!DOCTYPE html>
<html>
    <head>
    <style type="text/css">
     .rectangle {
         width: 50%;
         margin: 10px 0;
     }

     .box_sizing_border {
         box-sizing: border-box;
         padding: 0 30px;
         border: solid 5px #5f9;
     }

     .box_sizing_content_padding {
         box-sizing: content-box;
         padding: 0 30px;
     }

     .box_sizing_content_border {
         box-sizing: content-box;
         border: solid 5px #559;
     }
    </style>
    </head>
    <body>
    <div class="rectangle" style="background-color: #f90">
        width: 50%;
    </div>
    <div class="box_sizing_border rectangle" style="background-color: #599">
        width:50%;<br>
        box-sizing: border-box;<br>
        padding: 0 30px;<br>
        border: solid 5px #5f9;
    </div>
    <div class="box_sizing_content_border rectangle" style="background-color: #55f">
        width:50%;<br>
        box-sizing: content-box;<br>
        border: solid 5px #5f9;
    </div>
    <div class="box_sizing_content_padding rectangle" style="background-color: #55f">
        width:50%;<br>
        box-sizing: content-box;<br>
        padding: 0 30px;<br>
    </div>
    </body>
</html>

参考資料

HTMLクイックリファレンス

1
1
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
1
1