CSS的浮动属性和清除的实例教程

75 阅读3分钟

如何在CSS中使用`float`属性并进行清除

浮动在过去一直是一个非常重要的话题。

它被用于许多黑客和创造性的使用中,因为它是为数不多的可以真正实现一些布局的方法之一,同时还有表格。在过去,我们习惯于将侧边栏向左浮动,例如,将其显示在屏幕的左侧,并在主要内容上增加一些空白。

幸运的是,时代变了,今天我们有了Flexbox和Grid来帮助我们进行布局,而float又回到了它最初的范围:将内容放在容器元素的一侧,并使其兄弟姐妹在其周围显示出来。

float 属性支持3个值。

  • left
  • right
  • none (默认值)

假设我们有一个盒子,里面有一段文字,而且这段文字还包含一个图片。

这里有一些代码。

<div class="parent">
  <div class="child">
    <div class="box">
      <p>This is some random paragraph and an image. <img src="https://via.placeholder.com/100x100" /> The image is in the middle of the text. The image is in the middle of the text. The image is in the middle of the text. The image is in the middle of the text. The image is in the middle of the text. The image is in the middle of the text. The image is in the middle of the text. The image is in the middle of the text. The image is in the middle of the text.
      </p>
    </div>
  </div>
</div>
.parent {
  background-color: #af47ff;
  padding: 30px;
  width: 500px;
}

.child {
  background-color: #ff4797;
  padding: 30px;
}

.box {
  background-color: #f3ff47;
  padding: 30px;
  border: 2px solid #333;
  border-style: dotted;
  font-family: courier;
  text-align: justify;
  font-size: 1rem;
}

和视觉外观。

正如你所看到的,正常的流程默认认为图像是内联的,并在行中为它留出空间。

如果我们在图片上添加float: left ,再加上一些填充。

img {
  float: left;
  padding: 20px 20px 0px 0px;
}

这就是结果。

而这是我们应用浮动:右,并相应地调整填充的结果。

img {
  float: right;
  padding: 20px 0px 20px 20px;
}

一个浮动的元素被从页面的正常流程中移除,而其他内容则围绕它流动。

见Codepen上的例子

你并不局限于浮动的图片,也可以。在这里,我们用一个span 元素来切换图片。

<div class="parent">
  <div class="child">
    <div class="box">
      <p>This is some random paragraph and an image. <span>Some text to float</span> The image is in the middle of the text. The image is in the middle of the text. The image is in the middle of the text. The image is in the middle of the text. The image is in the middle of the text. The image is in the middle of the text. The image is in the middle of the text. The image is in the middle of the text. The image is in the middle of the text.
      </p>
    </div>
  </div>
</div>
span {
  float: right;
  margin: 20px 0px 20px 20px;
  padding: 10px;
  border: 1px solid black
}

而这就是结果。

清理

当你浮动一个以上的元素时会发生什么?

如果浮动时它们找到了另一个浮动的图像,默认情况下它们会一个挨着一个,水平地堆积起来。直到没有空间,它们将开始被堆叠在新的一行。

假设我们在一个p 标签内有3张内联图片。

如果我们给这些图片添加float: left

img {
  float: left;
  padding: 20px 20px 0px 0px;
}

这就是我们将得到的结果。

如果你在图片上添加clear: left ,这些图片将被垂直堆叠,而不是水平堆叠。

我把left 的值用于clear 。它允许

  • left 清除左边的漂浮物
  • right 清除右边的浮动
  • both 清除左右两边的浮动
  • none (默认)禁止清空