网络日志

九宫格的几种实现

一,利用flex布局

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<style>
    .c-row{
       display:flex;
       flex-direction: row;
    }
    .square{
        width: 43px;
        height:43px;
        line-height: 43px;
        border:1px solid silver;
        margin-right:-1px;
        margin-top:-1px;
    }
</style>
<body>
    <div class="c-div">
        <div class="c-row">
            <div class="square"></div>
            <div class="square"></div>
            <div class="square"></div>
        </div>
        <div class="c-row">
            <div class="square"></div>
            <div class="square"></div>
            <div class="square"></div>
        </div>
        <div class="c-row">
            <div class="square"></div>
            <div class="square"></div>
            <div class="square"></div>
        </div>
    </div>
    
</body>
</html>

二,利用浮动

1.父div设置left浮动,这样每个类是c-row的div是竖直向下排列的


    .c-row{
      float:left;
    }
    .square{
        width: 43px;
        height:43px;
        line-height: 43px;
        border:1px solid silver;
        margin-right:-1px;
        margin-top:-1px;
    }

2.每个square左浮动,利用父元素的伪类清除浮动

clear 属性只有块级元素才有效的,而 :after 等伪类及::after伪元素默认都是内联水平,这就是借助伪元素清除浮动影响时需要设置 display 属性值的原因。
  .c-row:after{
        clear:both;
        content:'';
        display:table;
        /*display:block*/
    }
    .square{
        float:left;
        width: 43px;
        height:43px;
        line-height: 43px;
        border:1px solid silver;
        margin-right:-1px;
        margin-top:-1px;
    }