技能测试:尺寸

本次技能测试的目的是帮助您评估是否理解 CSS 中设置元素尺寸 的不同方法。

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

任务 1

在此任务中,您有两个盒子。

完成任务

  1. 设置第一个盒子的尺寸,使其高度至少为 100px,即使内容较少导致其无法长到这个高度。但是,如果内容过多导致无法容纳在 100 像素内,内容也不应溢出。
  2. 通过移除 HTML 中的内容来测试此框,以确保即使没有内容,该框仍然具有 100px 的高度。
  3. 设置第二个盒子的尺寸,使其高度固定为 100px,因此如果内容过多,内容将会溢出。

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

Two boxes one with overflowing content

html
<div class="box box1">
  <p>
    Veggies es bonus vobis, proinde vos postulo essum magis kohlrabi welsh onion
    daikon amaranth tatsoi tomatillo melon azuki bean garlic. Gumbo beet greens
    corn soko endive gumbo gourd.
  </p>
</div>

<div class="box box2">
  <p>
    Veggies es bonus vobis, proinde vos postulo essum magis kohlrabi welsh onion
    daikon amaranth tatsoi tomatillo melon azuki bean garlic. Gumbo beet greens
    corn soko endive gumbo gourd.
  </p>
</div>
css
body {
  font: 1.2em / 1.5 sans-serif;
  padding: 1em;
}

.box {
  border: 5px solid black;
  width: 400px;
  margin-bottom: 1em;
}

.box1 {
  /* Add styles here */
}

.box2 {
  /* Add styles here */
}
点击此处显示解决方案

有两个盒子,第一个应该设置最小高度,在这种情况下,它会扩展以容纳额外的内容,但如果您移除一些内容,盒子至少会和 min-height 一样高。第二个盒子设置了固定高度,这会导致内容溢出。

css
.box1 {
  min-height: 100px;
}

.box2 {
  height: 100px;
}

任务 2

在此任务中,您有一个盒子,其中包含另一个盒子。

完成任务

  1. 使内部盒子的宽度为其外部盒子宽度的 60%box-sizing 属性的值设置为 border-box,这意味着总宽度包括任何内边距和边框。
  2. 为内部盒子设置 10% 的内边距,该百分比是根据宽度(或行内尺寸)计算的。

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

A box with another box nested inside

html
<div class="box">
  <div class="inner">Make me 60% of my parent's width.</div>
</div>
css
body {
  font: 1.2em / 1.5 sans-serif;
  padding: 1em;
}

.box {
  border: 5px solid black;
  width: 400px;
  margin-bottom: 1em;
}

.inner {
  background-color: rebeccapurple;
  color: white;
  border-radius: 5px;
}

* {
  box-sizing: border-box;
}
.inner {
  /* Add styles here */
}
点击此处显示解决方案

使盒子尺寸为容器的 60%,并设置四边 10% 的内边距。所有元素都已设置为 box-sizing: border-box,因此您无需担心使用哪种宽度。

css
* {
  box-sizing: border-box;
}
.inner {
  width: 60%;
  padding: 10%;
}

任务 3

在此任务中,您有两个图片,分别放置在两个盒子里。一张图片比盒子小,另一张图片比盒子大,并且溢出了盒子。

要完成此任务,请设想该盒子是响应式的,因此可以增大和缩小。对图片应用一个声明,使大图片缩小以适应盒子,但小图片不被拉伸。

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

Two boxes with images in

html
<div class="box">
  <img
    alt="A pink star"
    src="https://mdn.github.io/shared-assets/images/examples/star-pink_256x256.png" />
</div>

<div class="box">
  <img
    alt="Hot air balloons flying in clear sky, and a crowd of people in the foreground"
    src="https://mdn.github.io/shared-assets/images/examples/balloons.jpg" />
</div>
css
body {
  font: 1.2em / 1.5 sans-serif;
  padding: 1em;
}
.box {
  border: 5px solid black;
  margin-bottom: 1em;
  width: 500px;
}

img {
  /* Add styles here */
}
点击此处显示解决方案

示例中有一个溢出盒子的图片和一个小于盒子的图片,您需要设置 max-width 为 100%,使较大的图片只增大到盒子的大小。如果您使用 width: 100%,小图片将会被拉伸。

css
img {
  max-width: 100%;
}