🐷

CSS ボックスモデル

に公開

ボックスモデルの構造

  1. コンテンツエリア: 実際にテキストや画像が表示される部分。
  2. パディング: コンテンツエリアとボーダーの間の空白。内側のスペース。
  3. ボーダー: パディングとマージンの間にある枠線。
  4. マージン: ボーダーと他の要素の間の空白。外側のスペース。
+---------------------------+
|        マージン            |
|  +---------------------+  |
|  |      ボーダー        |  |
|  |  +---------------+  |  |
|  |  |   パディング    |  |  |
|  |  |  +---------+  |  |  |
|  |  |  | コンテンツ|  |  |  |
|  |  |  +---------+  |  |  |
|  |  +---------------+  |  |
|  +---------------------+  |
+---------------------------+

疑似要素 ::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

デフォルトの値
widthheight プロパティはコンテンツエリアだけに適用される。
パディングやボーダーは含まれない。

border-box

widthheight プロパティにコンテンツエリア、パディング、ボーダーが含まれる。

指定した幅や高さの中にパディングとボーダーも含まれる。

Discussion