← 第 1 关 – 建造者

第 9/12 课 ⏱ 30 分钟

Flexbox:真正的菜单

学会把盒子并排排列,你的菜单就会像真正网站上的那样。

跟我看:盒子并排

菜单里的链接现在像句子里的字一样一个接一个。真正的菜单会把项目 整齐地并排排列,有间距。CSS 有一个叫 flexbox 的工具用来排列盒子:

nav {
  display: flex;    /* this box's children line up side by side */
  gap: 16px;        /* space between them */
}

就这些。display: flex 告诉盒子:“把你的子元素(这里是链接)排成一行。” gap 设置它们之间的间距。Flexbox 还能做更多:

nav {
  display: flex;
  gap: 16px;
  justify-content: center;   /* center children horizontally */
  align-items: center;       /* also align them to the middle vertically */
  flex-wrap: wrap;           /* if they don't fit, wrap to the next line */
}

跟我看:像真正网站那样的菜单

把你知道的一切和 flexbox 结合起来:

header {
  background-color: #1d4ed8;   /* a colored bar at the top */
  padding: 16px;
}

header h1 {
  color: white;
  margin: 0;                   /* heading without its default spacing */
}

nav {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
  margin-top: 8px;
}

nav a {
  color: white;
  text-decoration: none;       /* remove the underline from links */
  padding: 8px 14px;
  border-radius: 999px;        /* fully rounded ends = a pill shape */
  background-color: rgba(255, 255, 255, 0.15);  /* semi-transparent white */
}

nav a:hover {
  background-color: rgba(255, 255, 255, 0.35);
}

最后有个新东西::hover 意思是”鼠标悬停在上面时”。菜单项悬停时会亮起来——就像你熟悉的网站一样。

轮到你了 💪

把菜单变成真正的菜单:页眉全宽彩色条,项目像药丸一样并排,悬停时亮起。颜色用第 6 课你选的配色。

🏫 学校网站——参考答案(蓝色)
header {
  background-color: #1d4ed8;
  padding: 16px;
}

header h1 { color: white; margin: 0; }

nav {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
  margin-top: 8px;
}

nav a {
  color: white;
  text-decoration: none;
  padding: 8px 14px;
  border-radius: 999px;
  background-color: rgba(255, 255, 255, 0.15);
}

nav a:hover { background-color: rgba(255, 255, 255, 0.35); }
🙋 个人网站——参考答案(橙色)

同样的代码,只换页眉颜色:

header {
  background-color: #ea580c;
  padding: 16px;
}
🌍 旅行日记——参考答案(绿色)

同样的代码,只换页眉颜色:

header {
  background-color: #15803d;
  padding: 16px;
}
⚽ 俱乐部网站——参考答案(俱乐部颜色)

同样的代码,只换页眉颜色为你的俱乐部色:

header {
  background-color: #b91c1c;
  padding: 16px;
}
💡

想要名字在左、菜单在右、同一行吗? 给页眉再包一层 flexbox:加 header { display: flex; justify-content: space-between; align-items: center; }space-between 意思是”把子元素推开:第一个靠左,最后一个靠右”。

检查一下: 网站顶部有彩色条,白色名字和药丸形菜单项,悬停时会亮。记住——因为 CSS 是共享的,每个页面的菜单一次就全改了。

这堂课你要记住