← レベル1 – ビルダー

レッスン 8/12 ⏱ 30 分

ボックスと余白

CSS の最大の秘密:ページ上のすべてはボックス。動かし方を学ぼう。

見てみよう:すべてがボックス

ウェブデザイン最大の秘密:ページ上のすべてが四角いボックス。 見出し、段落、画像、メニュー——全部。これが見えたら CSS が全部つながる。

各ボックスには3種類の余白がある:

        margin (outer space)
      ┌─────────────────────────┐
      │  border (frame)         │
      │  ┌───────────────────┐  │
      │  │ padding (cushion) │  │
      │  │  ┌─────────────┐  │  │
      │  │  │   CONTENT   │  │  │
      │  │  └─────────────┘  │  │
      │  └───────────────────┘  │
      └─────────────────────────┘
.card {
  padding: 16px;        /* cushion on all sides */
  border: 2px solid gray;
  margin: 20px 0;       /* 20px top and bottom, 0 on the sides */
  border-radius: 12px;
}

見てみよう:プロみたいなページ

本物のサイトで見たことある——コンテンツが画面いっぱいに広がらず、真ん中の快適な列に収まる。CSS 3行で:

main {
  max-width: 700px;   /* content will never be wider than 700px */
  margin: 0 auto;     /* auto on the sides = center it */
  padding: 0 16px;     /* on mobile, text won't be glued to the edge */
}

margin: 0 auto は魔法の公式:上下ゼロ、左右「自動で均等」= 中央寄せ。世界中のサイトがほぼこれを使う。

画像も制御——ページからはみ出さないように:

img {
  max-width: 100%;      /* never wider than the column */
  height: auto;         /* height adjusts automatically, so the photo doesn't squish */
  border-radius: 12px;  /* rounded corners suit every photo */
}

やってみよう 💪

どのプロジェクトでも同じ課題——どんなサイトにも使える汎用スタイル:

  1. コンテンツを中央に:mainmax-width + margin: 0 auto
  2. 例の img ルールで画像を制御。
  3. 前レッスンのバッジを改善:margin で呼吸する余白を。
  4. ページに余裕を:body { line-height: 1.6; }——行間が広がって読みやすく。
完全な答え(どのプロジェクトでも使える)

style.css に追加:

body {
  line-height: 1.6;
}

main {
  max-width: 700px;
  margin: 0 auto;
  padding: 0 16px;
}

img {
  max-width: 100%;
  height: auto;
  border-radius: 12px;
}

バッジ(.news.favorite.tip.win など)にこの行を追加:

  margin: 20px 0;
💡

ボックスを見えるようにしてみよう! 一時的に CSS にこのルールを追加:* { border: 1px solid red; }——アスタリスクは「全部」。突然ページ上のすべてのボックスが見える。消す前にその景色を覚えて——ブラウザはそうやってページを見てる。

確認: コンテンツが中央の快適な列に、写真は角丸ではみ出さない、テキストは読みやすい。ブラウザを狭く——コンテンツが調整される。サイトが一段上の見た目に。

このレッスンのまとめ