浮动

127 阅读1分钟

浮动

属性:float;

属性值:

  1left       元素向左浮动
  2right      元素向右浮动
  3none       默认值,不浮动
  4:inherit    从父元素继承
  

特点:

  1:脱离文档流,不占位
  2:使行内元素变成行内块元素
  3:块元素在一行显示
  

清除浮动

  1:给受到影响的父元素添加overflow:hidden;因为overf属性会触发BFC;
  BTC:block formatting context 块级格式化上下文-让元素强制安装块元素的规则进行排列

`<style>
  
    .box1{
    
        width: 100px;
        
        height: 100px;
        
        background-color: red;
        
        float: left;
        
    }

    .box2{
    
        width: 200px;
        
        height: 200px;
        
        background-color: seagreen;
        
        /* float: left; */
        
        overflow: hidden;
        
    }
    </style>
    
<div class="box">

    <div class="box1"></div>

    <div class="box2"></div>

</div>
`
  2:在受到影响浮动的元素前面,添加一个空div,给空div添加样式:clear:both

`

    .box1{
    
        width: 100px;
        
        height: 100px;
        
        background-color: red;
        
        float: left;
        
    }

    .box2{
    
        width: 200px;
        
        height: 200px;
        
        background-color: seagreen;
        
        /* float: left; */
        
    }

    .clearfix{
    
        clear:both;
        
    }
</style>
<div class="box">

    <div class="box1"></div>

    <div class="clearfix"></div>

    <div class="box2"></div>

</div>
` 3:在浮动元素的父标签的伪元素选择器:after中清除浮动-类似于空div

`

    .box1{

        width: 100px;

        height: 100px;

        background-color: red;

        float: left;

    }

    .box2{

        width: 200px;

        height: 200px;

        background-color: seagreen;

        float: left;

    }

    .box:after{

        content: "";

        display: block;

        clear: both;

    }

</style>
<div class="box">

    <div class="box1"></div>

    <div class="box2"></div>

</div>
`