CSSで横幅を指定しても「padding」や「border」を入れることで、指定した横幅以上に広がってしまう事があります。
そこで「padding」や「border」を記述した場合とその見え方、解決方法を順に解説します。
「padding」と「border」無し

HTML(共通)
<div class="box">
<p>BOXの中</p>
</div>
<p>BOXの中</p>
</div>
CSS(「padding」「border」無し)
.box {
width: 500px;
height: 200px;
margin: 50px auto;
display: flex;
justify-content: center;
align-items: center;
background: #e2e2e2;
}
width: 500px;
height: 200px;
margin: 50px auto;
display: flex;
justify-content: center;
align-items: center;
background: #e2e2e2;
}
「padding」を入れた場合

CSS(「padding」あり)
.box {
width: 500px;
height: 200px;
margin: 50px auto;
display: flex;
justify-content: center;
align-items: center;
background: #e2e2e2;
padding: 20px;
}
width: 500px;
height: 200px;
margin: 50px auto;
display: flex;
justify-content: center;
align-items: center;
background: #e2e2e2;
padding: 20px;
}
「padding」と「border」を入れた場合

CSS(「padding」と「border」あり)
.box {
width: 500px;
height: 200px;
margin: 50px auto;
display: flex;
justify-content: center;
align-items: center;
background: #e2e2e2;
padding: 20px;
border: 20px solid #ff9f2e;
}
width: 500px;
height: 200px;
margin: 50px auto;
display: flex;
justify-content: center;
align-items: center;
background: #e2e2e2;
padding: 20px;
border: 20px solid #ff9f2e;
}
解決の記述を入れた場合

CSS(「box-sizing」あり)
.box {
width: 500px;
height: 200px;
margin: 50px auto;
display: flex;
justify-content: center;
align-items: center;
background: #e2e2e2;
padding: 20px;
border: 20px solid #ff9f2e;
box-sizing: border-box;
}
width: 500px;
height: 200px;
margin: 50px auto;
display: flex;
justify-content: center;
align-items: center;
background: #e2e2e2;
padding: 20px;
border: 20px solid #ff9f2e;
box-sizing: border-box;
}
「box-sizing: border-box;」を1行加えることで、この問題が解決されます。
なお、必要なBOXごとに記述するより、リセット用のCSSに書いてしまうと楽です。
その場合は下記の記述になります。
CSS(リセット用の記述)
*,
*::before,
*::after {
box-sizing: border-box;
}
*::before,
*::after {
box-sizing: border-box;
}
この「box-sizing」は「CSS3」から追加された便利なプロパティです。