CSS 浮动基本概念

浮动在CSS布局中扮演关键角色,通过float属性实现元素移出正常流并影响周围内容布局。文章探讨了浮动元素的特性,包括文本环绕、外边距不合并以及包含块的概念,通过实例展示了浮动如何改变元素位置和间距。了解这些基础知识有助于提升CSS布局能力。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

浮动在文档布局中是一个非常重要的概念,CSS 允许浮动任何元素。

浮动属性 float

定义
指定元素在哪个方向上浮动。
属性值
  • left - 元素向左浮动

  • right - 元素向右浮动

  • none - 元素不浮动,并且会显示在其在文本中出现的位置

  • inherit - 从父元素继承属性值

浮动的特性

1. 浮动元素会被从正常文档流中删除,不过还是会影响文档的布局

css:

.float_right {

    float: right;

}

html:    

<p>

    When the farmer was old, and felt that his time had come to die, he called the three sons to him and said, <img src="./images/gold.jpg" class="float_right" /> "My sons, there is a pot of gold hidden in the olive orchard. Dig for it, if you wish it."

</p>

如代码所示,文本中插入了一个向右浮动的图片,运行效果如下:


可以看出图片出现的位置不是其在文本中声明的位置。不过也是由于图片的浮动,所以其他文本的位置出现了变化。之所以会出现这样的效果,是因为当一个元素浮动时,其他内容会环绕该元素。

2. 浮动元素周围的外边距不会被合并

css:

img {

    margin20px;

    width300px;

    height200px;

}


.float_left {

    float: left;

    border1px solid yellow;

}


.control-text {

    margin20px;

    border1px solid blue;

}

html:

<p class="control-text">

    They dug until they had turned up the soil from one end of the orchard to the other, round the tree-roots and between them. But no pot of gold was to be found. It    seemed as if someone must have stolen it, or as if the farmer had been wandering in his wits. The three sons were bitterly disappointed to have all their work for nothing.

</p>

<img src="./images/labor.jpg" class="float_left" />

<p class="control-text">

    The next olive season, the olive trees in the orchard bore more fruit than they

    had ever given; when it was sold, it gave the sons a whole pot of gold.

</p>

代码中为文本元素和图片同时添加了外边距,运行效果如下:


如图,两个文本片段设置了 margin,它们之间的 margin 被合并为了一个。而由于图片设置了 float 属性,文本和图片之间的 margin 是各自独立的。

3. 距离浮动元素最近的块级祖先元素是它的包含块

4. 浮动元素会生成一个块级框,不管它本身是什么


更多 CSS 技巧,请关注微信公众号



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值