技能测试:浮动

本次技能测试旨在帮助您评估是否理解 CSS 中的浮动,包括 floatclear 属性及其值,以及清除浮动的其他方法。您将完成三个小型任务,这些任务使用了您刚刚学到的内容的各个方面。

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

任务 1

要完成此任务,请分别将类名为 float1float2 的两个元素向左和向右浮动。然后,文本将显示在两个框之间,如下图所示。

Two blocks displaying left and right of some text.

html
<div class="box">
  <div class="float float1">One</div>
  <div class="float float2">Two</div>
  <p>The two boxes should float to either side of this text.</p>
</div>
css
body {
  font: 1.2em / 1.5 sans-serif;
}

* {
  box-sizing: border-box;
}

.box {
  padding: 0.5em;
}

.float {
  margin: 15px;
  width: 150px;
  height: 150px;
  border-radius: 5px;
  background-color: rebeccapurple;
  color: white;
  padding: 1em;
}

.float1 {
  /* Add styles here */
}

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

您可以为两个框都使用 float

css
.float1 {
  float: left;
}

.float2 {
  float: right;
}

任务 2

要完成此任务

  1. 将类名为 float 的元素向左浮动。
  2. 更新代码,使第一行文本显示在该元素旁边,而下一行文本(类名为 below)显示在其下方。

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

A box displayed to the left of a line of text, with some more text below.

html
<div class="box">
  <div class="float">Float</div>
  <p>This sentence appears next to the float.</p>
  <p class="below">Make this sentence appear below the float.</p>
</div>
css
body {
  font: 1.2em / 1.5 sans-serif;
}

* {
  box-sizing: border-box;
}

.box {
  padding: 0.5em;
}

.float {
  margin: 15px;
  width: 150px;
  height: 150px;
  border-radius: 5px;
  background-color: rebeccapurple;
  color: white;
  padding: 1em;
}

.float {
  /* Add styles here */
}

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

您需要将该项目向左流动,然后为第二个段落的类添加 clear: left

css
.float {
  float: left;
}

.below {
  clear: left;
}

任务 3

在此任务中,我们有一个浮动元素。包裹浮动元素和文本的框显示在浮动元素后面。

要完成此任务,请使用最新的可用方法使框的背景扩展到浮动元素下方,如下图所示。

A block displayed to the right of some text both wrapped by a box with a background color.

html
<div class="box">
  <div class="float">Float</div>
  <p>This sentence appears next to the float.</p>
</div>
css
body {
  font: 1.2em / 1.5 sans-serif;
}

* {
  box-sizing: border-box;
}

.box {
  padding: 0.5em;
}

.float {
  margin: 15px;
  width: 150px;
  height: 150px;
  border-radius: 5px;
  background-color: rgb(207 232 220);
  padding: 1em;
  color: white;
}

.box {
  background-color: rebeccapurple;
  padding: 10px;
  color: white;
}

.float {
  float: right;
}

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

通过向 .box 的类添加 display: flow-root 来清除浮动项下方的框。其他方法可能包括使用 overflow 或 clearfix hack,但学习资料中将 flow-root 方法作为实现此目的的现代方式进行了介绍。

css
.box {
  display: flow-root;
}