← 第 1 关 – 建造者

第 8/12 课 ⏱ 30 分钟

盒子和间距

发现 CSS 里最大的秘密:页面上的一切都是盒子。并学会移动它们。

跟我看:一切都是盒子

网页设计里最大的秘密:页面上每一样东西都是长方形的盒子。 标题、段落、图片、菜单——全是。一旦你能这样看,整个 CSS 就通了。

每个盒子周围有三种空间:

        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 就能做到:

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. 居中内容:在 main 上用 max-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; }——星号表示”所有东西”。突然你会看到页面上每个盒子。然后再删掉,但记住那个画面:浏览器就是这样看你的页面的。

检查一下: 内容在舒适的居中列里,照片有圆角、不会到处溢出,文字好读。缩小浏览器窗口——内容会自适应。你的网站突然高了一个档次。

这堂课你要记住