CSS 中的浮动

作者: 肆意木 | 来源:发表于2017-10-09 21:55 被阅读60次

    浮动的定义:

    元素脱离文档流

    举栗子:

    //HTML
    
    <!DOCTYPE html>
    <html>
    <head>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width">
      <title>JS Bin</title>
    </head>
    <body>
    <div class="home">
      <div class="left">left</div>
      <div class="center">center</div>
      <div class="right">right</div>
    </div>
    </body>
    </html>
    
    //CSS
    
    .home{
      border:1 px solid;
      margin:50px auto;
      padding:50px;
      background: red;
    }
    .left{
      height:80px;
      width:80px;
      background:blue;
      float:left;
    }
    .right{
      height:80px;
      width:80px;
      background:yellow;
      float:left;
    }
    .center{
      height:80px;
      width:80px;
      background:green;
      float:left;
    }
    
    
    1.png

    修改 CSS 代码,清除浮动:

    .home{
      border:1 px solid;
      margin:50px auto;
      padding:50px;
      background: red;
    }
    .left{
      height:80px;
       width:80px;
      background:blue;
    }
    .right{
      height:80px;
      width:80px;
      background:yellow;
    }
    .center{
      height:80px;
     width:80px;
      background:green;
    }
    
    1.png

    浮动的影响:

    父元素高度塌陷

    清除浮动:

    1.在浮动的子元素后面添加一个空的 div 设置属性 clear :both(在左右两侧均不允许浮动元素)或者可以试着添加空行 br 效果等同于div 设置 clear:both;

    //HTML
    <!DOCTYPE html>
    <html>
    <head>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width">
      <title>JS Bin</title>
    </head>
    <body>
    <div class="home">
      <div class="left">left</div>
      <div class="center">center</div>
      <div class="right">right</div>
      <div class='test'></div>
    //<br clear="both">
    </div>
    </body>
    </html>
    
    //添加CSS
    
    .test{
      clear:both;
    }
    
    1.png

    2.给父元素设置宽和高,但是如果父元素宽和高不确定这个方法就不适用

    //修改 CSS
    
    .home{
      border:1 px solid;
      margin:50px auto;
      padding:50px;
      background: red;
      width:500px;
      height:100px
    }
    
    1.png

    3.给父元素设置浮动,但是如果可能会引起新的问题,而且需要给每个父元素都设置浮动。

    //修改 CSS
    .home{
      border:1 px solid;
      margin:50px auto;
      padding:50px;
      background: red;
      float:left
    }
    
    1.png

    4.给父级添加 overflow:hidden 清浮动方法

    //修改 CSS
    .home{
      border:1 px solid;
      margin:50px auto;
      padding:50px;
      background: red;
      overflow:hidden
    }
    
    1.png

    5.伪类清除浮动,在父容器的尾部自动创建一个子元素

    //添加 CSS
    :after{
      content:".";
      clear:both;
      display:block;
      height:0;
      overflow:hidden;
      visibility:hidden;
    }
    
    1.png

    相关文章

      网友评论

        本文标题:CSS 中的浮动

        本文链接:https://www.haomeiwen.com/subject/phtpyxtx.html