css中的浮动(float)

在css中设置float属性可以使元素脱离标准文档流(标准文档流指的是HTML页面在没有设置任何css样式的情况下,块级元素从上到下,行内元素从左到右依次排列的情况),但在最开始的时候,float属性只是为了达到文字环绕的效果。

float属性不能继承,可以设置以下值:

1、left,元素向左浮动。

2、right,元素向右浮动。

3、none,默认值。元素不浮动,并会显示在其在文本中出现的位置。

当元素不设置float属性时,默认排版为从上到下:

css部分代码为:

<style type="text/css">
 div{
     outline:1px solid black;
    }
.box_father{
    width: 300px;
    background-color: aliceblue;
    text-align:center;
    line-height:150px;
    color:red;
    }
.box_son1{
     height:150px;
     width:150px;
     background-color: antiquewhite;
    }
.box_son2{
     height:150px;
     width:150px;
     background-color:beige;
    }
</style>

 

当元素设置了float:left;之后:

此时父元素的高度塌陷,height为0,如图:

右边浮动同理:

 

可以给父元素一个指定的高度,或者设置overflow:hidden;父元素的高度就会撑起来了。

<style type="text/css">
 div{
     outline:1px solid black;
    }
.box_father{
    width: 300px;
    overflow:hidden;
    background-color: aliceblue;
    text-align:center;
    line-height:150px;
    color:red;
    }
.box_son1{
     height:150px;
     width:150px;
     background-color: antiquewhite;
     float:right;
    }
.box_son2{
     height:150px;
     width:150px;
     background-color:beige;
     float:right;
    }
</style>

或者在浮动元素的后面添加一个空元素,设置clear:both;

<style type="text/css">
 div{
     outline:1px solid black;
    }
.box_father{
    width: 300px;
    overflow:hidden;
    background-color: aliceblue;
    text-align:center;
    line-height:150px;
    color:red;
    }
.box_son1{
     height:150px;
     width:150px;
     background-color: antiquewhite;
     float:right;
    }
.box_son2{
     height:150px;
     width:150px;
     background-color:beige;
     float:right;
    }
.box_clear{
     clear:both;
    }
</style>

最后总结一下:

float有以下特性:

1、包裹性

2、子元素浮动会导致父元素的高度塌陷

3、元素浮动会对周围的盒子产生影响

清除浮动的三个方法:

1、给父元素设置overflow:hidden;

2、给父元素设置一个合适的高度,让他自己撑起来。

3、在浮动元素的末尾增加一个空的div设置clear:both;但这种方法会新增多余的标签。

 

转载于:https://www.cnblogs.com/lurending0417/p/7441337.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值