LoginSignup
15
13

More than 5 years have passed since last update.

CSSでのwidth指定ではみ出る場合の原因と対応について

Posted at

原因

widthは内容(Content)だけに適用される。 実際の横幅は Content, Padding, Border の幅合計になる。

widthに100%且つPaddingかBorderがサイズ指定されている場合などは横幅が親より大きくなる。

対応策

CSSの box-sizing プロパティを設定することで、width算出挙動を指定することができる。

先述のプロパティに border-box を指定することで、widthが実際の横幅になる。(Content幅は width - Padding + Border になる)

※border-sizingはIE8から利用可能。今ならたいていの場面で使用可能なはず。

確認用HTML

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>SizeBoxing</title>
    <style>
        .container{
            width: 600px;
            height: 120px;
            border: 1px solid #000;
            background: #b6ff00;
            margin: 0 auto;
            margin-top: 50px;
        }

        .box1{
            width:100%; /* "Content"を親のWidthと同じ(600px)にする */
            background:#ff6a00;
            padding: 10px;
        }

        .box2{
            width:100%; /* "Content"+"border"+"padding" を親のWidthと同じ(600px)にする */
            background:#0f30ce;
            color: #f8f7f7;
            padding: 10px;
            box-sizing: border-box;
            border: 2px solid #ff0000;
        }

    </style>
</head>
<body>

    <div class="container">
        <p>はみ出る</p>
        <div class="box1">あああああああああああああああああああああああああああああああああああああああああああああ</div>
    </div>


    <div class="container">
        <p>はみ出ない</p>
        <div class="box2">いいいいいいいいいいいいいいいいいいいいいいいいいいいいいいいいいいいいいいいいいいいいい</div>
    </div>

</body>
</html>

参考資料

15
13
0

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
15
13