🐷
CSS ボックスモデル
ボックスモデルの構造
- コンテンツエリア: 実際にテキストや画像が表示される部分。
- パディング: コンテンツエリアとボーダーの間の空白。内側のスペース。
- ボーダー: パディングとマージンの間にある枠線。
- マージン: ボーダーと他の要素の間の空白。外側のスペース。
+---------------------------+
| マージン |
| +---------------------+ |
| | ボーダー | |
| | +---------------+ | |
| | | パディング | | |
| | | +---------+ | | |
| | | | コンテンツ| | | |
| | | +---------+ | | |
| | +---------------+ | |
| +---------------------+ |
+---------------------------+
::before
と ::after
の配置
疑似要素 ::before
と ::after
は、要素のコンテンツエリアの前後に追加される擬似要素。
そのため、borderの外側を起点にすることはできない。borderの外側を起点にしたい場合、borderの幅分をマイナスする必要がある。
マイナスするプロパティはleft、margin-left,transform:translateX();、などなんでもいい。
コード例
コンテンツエリアが基準になる
<div class="box"></div>
.box {
position: relative;
width: 100px;
height: 100px;
border: 5px solid black;
margin-top: 20px;
margin-left: 20px;
background-color: blue;
&::before {
position: absolute;
top: 0;
left: 0;
width: 60px;
height: 60px;
background-color: red;
content: '';
}
}
ボーダーの外側を基準にしたい場合
<div class="box"></div>
.box {
position: relative;
width: 100px;
height: 100px;
border: 5px solid black;
margin-top: 20px;
margin-left: 20px;
background-color: blue;
&::before {
position: absolute;
top: -5px;
left: -5px;
width: 60px;
height: 60px;
background-color: red;
content: '';
}
}
box-sizing
プロパティ
要素のサイズをどのように計算するかを決定するための CSS プロパティ。
content-box
デフォルトの値。
width
と height
プロパティはコンテンツエリアだけに適用される。
パディングやボーダーは含まれない。
border-box
width
と height
プロパティにコンテンツエリア、パディング、ボーダーが含まれる。
指定した幅や高さの中にパディングとボーダーも含まれる。
Discussion