测试你的技能:盒模型

本次技能测试的目的是帮助你评估是否理解CSS 盒模型

注意: 如需帮助,请阅读我们的“技能测试”使用指南。您也可以通过我们的沟通渠道与我们联系。

互动挑战

首先,我们为你提供一个有趣的、涉及外边距简写法的交互式挑战,它由我们的学习伙伴 Scrimba 创建。

观看嵌入的 scrim,并按照说明编辑代码,完成时间轴上的任务(小幽灵图标)。完成后,你可以继续观看 scrim,检查老师的解决方案是否与你的相匹配。

任务 1

在此任务中,下方有两个框,一个使用了标准的盒模型,另一个使用了替代盒模型。我们希望你通过向 .alternate 类添加声明来改变第二个框的宽度,使其与第一个框的视觉宽度相匹配。

您的最终结果应如下面的图片所示

Two boxes of the same size

html
<div class="box">I use the standard box model.</div>
<div class="box alternate">I use the alternate box model.</div>
css
body {
  font: 1.2em / 1.5 sans-serif;
}
.box {
  border: 5px solid rebeccapurple;
  background-color: lightgray;
  padding: 40px;
  margin: 40px;
  width: 300px;
  height: 150px;
}

.alternate {
  box-sizing: border-box;
}
点击此处显示解决方案

你需要增加第二个块的宽度,以加上内边距和边框的大小

css
.alternate {
  box-sizing: border-box;
  width: 390px;
}

任务 2

要完成此任务,请向提供的框添加以下属性:

  • 一个 5px 的黑色虚线边框。
  • 顶边距为 20px
  • 右边距为 1em
  • 底边距为 40px
  • 左边距为 2em
  • 所有边内边距均为 1em

您的最终结果应如下面的图片所示

A box with a dotted border

html
<div class="box">I use the standard box model.</div>
css
body {
  font: 1.2em / 1.5 sans-serif;
}

.box {
}
点击此处显示解决方案

此任务涉及正确使用外边距、边框和内边距属性。你可以选择使用长格式属性(margin-topmargin-right 等),但当设置所有边距和内边距时,简写形式可能是更好的选择。

css
.box {
  border: 5px dotted black;
  margin: 20px 1em 40px 2em;
  padding: 1em;
}

任务 3

在此任务中,行内元素具有外边距、内边距和边框。但是,其上方和下方的行与之重叠。

要完成此任务,请更新 CSS,使其他行尊重外边距、内边距和边框的大小,同时保持元素为行内元素。

您的最终结果应如下面的图片所示

An inline box with space between it and the text around it.

html
<div class="box">
  <p>
    Veggies es bonus vobis, <span>proinde vos postulo</span> essum magis
    kohlrabi welsh onion daikon amaranth tatsoi tomatillo melon azuki bean
    garlic.
  </p>

  <p>
    Gumbo beet greens corn soko endive gumbo gourd. Parsley shallot courgette
    tatsoi pea sprouts fava bean collard greens dandelion okra wakame tomato.
    Dandelion cucumber earthnut pea peanut soko zucchini.
  </p>
</div>
css
body {
  font: 1.2em / 1.5 sans-serif;
}

.box span {
  background-color: pink;
  border: 5px solid black;
  padding: 1em;
}
点击此处显示解决方案

解决此任务需要理解何时使用不同的 display 值。添加 display: inline-block 后,块方向的外边距、边框和内边距将使其他行远离该元素。

css
.box span {
  background-color: pink;
  border: 5px solid black;
  padding: 1em;
  display: inline-block;
}