css 实现三等分布局

1,399 阅读1分钟

已知

<html>
<head>
    <title>三等分布局</title>
    <style>
        body{
            margin: 0;
            padding: 0;
        }
        .outer{
        }
        .inner{ 
            height: 300px; 
        }
        .left{
            background-color: yellowgreen; 
        }
        .center{
            background-color: gainsboro; 
        }
        .right{
            background-color: burlywood; 
        }
    </style>
</head>
<body>
    <div class="outer">
        <div class="inner left"></div>
        <div class="inner center"></div>
        <div class="inner right"></div>
    </div>
</body>
</html>

请写出样式 outer和inner的实现。

1 行内布局inline-block + 百分比宽度

使用行内布局inline-block + 内部box为百分比宽度33.33%。

    .outer{ 
    }
    .inner{
        width: 33.33%; 
        height: 300px;
        display: inline-block;  
    }

image.png 结果出现空白间隔,导致第三个box下移了。

原因

html的每个子box之间有换行符存在

image.png

解决方案

  1. 删除多空文本,但是排版不好看 image.png
  2. 设置父容器font-size:0;使换行符的占位空间为0
    .outer{
        font-szie:0; /*新增font-szie设置,使换行符的占位空间为0*/
    }

image.png

2 float:left + 百分比宽度

跟方法1 行内布局同理,只是通过float:left实现行内布局

 .outer{ 
    font-size: 0;
}
.inner{
    width: 33.33%; 
    height: 300px;  
    float: left;
}

3 flexbox

使用flex布局+ flex:1 自动平分剩余空间

.outer{
    display: flex;
}
.inner{
    background-color: antiquewhite; 
    height: 300px;
    flex: 1;
}

image.png

4 gird

.outer{ 
    display: grid;
    grid-template-columns: 1fr 1fr 1fr;
   /* 等价于 grid-template-columns: repeat(3,1fr);*/  
}

image.png

5 dispaly:table,table-cell + 百分比宽度

父级设置dispaly:table,子box设置table-cell,变成table的结构

.outer{ 
    width: 100%;
    display: table;
}
.inner{
    display: table-cell;
    width: 33.33%; 
    height: 300px;   
}

6 <table>标签 + 百分比宽度

需要改变原来的dom结构

    <style>
        .outer{ 
            width: 100%; /*给table确定宽度*/
            border-collapse:collapse; /*去除table空隙*/
        }
        .inner{ 
            width: 33.33%; 
            height: 300px; 
        }
    </style>
<body> 
       <table class="outer" >
           <tr>
               <td class="left inner"></td>
               <td class="center inner"></td>
               <td class="right inner"></td>
           </tr>
       </table> 
</body>

7 绝对定位absolute + 百分比宽度

子box设置为position:absolute,宽度设置为对应的left:0 , left:33.33% , left:66.66%

.outer{
}
.inner{
    width: 33.33%; 
    height: 300px;
    position:absolute;
}
.left{
    background-color: yellowgreen;
    left: 0;
}
.center{
    background-color: gainsboro;
    left: 33.33%;
}
.right{
    background-color: burlywood; 
    left: 66.66%;
}

8 固定定位fixed + 百分比宽度

跟absolute同理 fixed也能实现

.outer{
}
.inner{
    width: 33.33%; 
    height: 300px;
    position:fixed;
}
.left{
    background-color: yellowgreen;
    left: 0;
}
.center{
    background-color: gainsboro;
    left: 33.33%;
}
.right{
    background-color: burlywood; 
    left: 66.66%;
}