CSS float属性

浮动在CSS中一直是一个非常重要的话题。

它被用在很多有创造性的用法中,因为它是为数不多的几种方法之一,和表格一样,我们可以真正实现一些布局。例如,在过去,我们常常将侧边栏浮动到左边,以便在屏幕的左侧显示它,并为主要内容添加一些边距。

幸运的是,时代变了,今天我们有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;
}

显示的效果如下:

CSS float属性

如您所见,默认情况下,正常的流将以内联方式考虑图像,并在行中为其留出空间。

如果我们给图像添加float: left和一些padding:

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

结果如下:

CSS float属性

下面是通过float:right,调整padding,得到的结果如下:

img {
  float: right;
  padding: 20px 0px 20px 20px;
}
CSS float属性

浮动元素从页面的正常流中移除,其他内容围绕它流动。

您也不局限于浮动图像,这里我们用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
}

结果如下:

CSS float属性
(0)
上一篇 2020年10月20日 下午5:32
下一篇 2020年10月20日 下午11:52

相关推荐

发表回复

登录后才能评论