假设高度已知,左右宽度固定,实现三栏布局的5种方法

24次阅读

共计 2164 个字符,预计需要花费 6 分钟才能阅读完成。

第一种方法 float
<style>
*{
padding:0;
margin:0;
}
.big div{
height:100px;
}
.big .left{
width:300px;
float:left;
background:red;
}
.big .right{
width:300px;
float:right;
background:yellow;
}
.big .center{
background:blue;
}
</style>

<div class=”big”>
<div class=”left”>

</div>
<div class=”right”>

</div>
<div class=”center”>
浮动解决方案
</div>
</div>
第一种解决方案基本上没有什么难度,平时应该也会用到很多!
第二种方法:absolute
<style>
.position{
margin-top:10px;
}
.position>div{
position:absolute;
height:100px;
}
.position .left{
left:0;
width:300px;
background:red;
}
.position .right{
right:0;
width:300px;
background:yellow;
}
.position .center{
left:300px;
right:300px;
background:blue;
}
</style>
<div class=”position”>
<div class=”left”>

</div>
<div class=”right”>

</div>
<div class=”center”>
绝对定位方案 2
</div>
</div>

第二种方法也是轻松实现效果。
第三种方法:flexbox
<style>
.flex{
margin-top:120px;
display:flex;
}
.flex>div{
height:100px;
}
.flex .left{
width:300px;
background:red;
}
.flex .center{
flex:1;
background:blue;
}
.flex .right{
width:300px;
background:yellow;
}
</style>

<div class=”flex”>
<div class=”left”>

</div>
<div class=”center”>
flex 方案
</div>
<div class=”right”>

</div>
</div>

第四种方法:表格布局
<style>
.table{
margin-top:10px;
width:100%;
display:table;
height:100px;
}
.table>div{
display:table-cell;
}
.table .left{
width:300px;
background:red;
}
.table .center{
background:blue;
}
.table .right{
width:300px;
background:yellow;
}
</style>

<div class=”table”>
<div class=”left”>

</div>
<div class=”center”>
table 方案
</div>
<div class=”right”>

</div>
</div>
table 方案同样实现,只是现在我们可能已经很少使用表格布局了。页面渲染性能也要差一点!
第五种方法:网格布局 grid
<style>
.grid{
margin-top:10px;
display:grid;
width:100%;
grid-template-rows:100px;
grid-template-columns: 300px auto 300px;
}
.grid .left{
background:red;
}
.grid .center{
background:blue;
}
.grid .right{
background:yellow;
}
</style>

<body>
<div class=”grid”>
<div class=”left”>

</div>
<div class=”center”>
grid 方案
</div>
<div class=”right”>

</div>
</div>
</body>
网格布局方法也实现了,CSS3 的网格布局有点类似于 bootstrap 的栅格化布局,都是以网格的方式来划分元素所占的区块。
问题没有结束,我们继续讨论。五种解决方案哪一个更好呢?笔者一直认为技术没有好坏之分,完全取决于你用在什么地方。
五种方法的优缺点:

浮动:兼容性好,如果对兼容性有明确的要求使用浮动应该满足需求,但是一定要处理好与周边元素的关系,因为一不注意浮动就可能造成页面布局混乱等问题,不过解决浮动带来的副作用方法也不少这里我们不做讨论。
绝对定位:简单直接,但是会使父元素脱离正常文档流里面的子元素也会跟着脱离。
flex: 目前看来比较完美,不过现在稍微完美一点的技术都存在或多或少的兼容性问题,同样这个样式 IE8 下是不支持的!(IE 呀!)
表格布局:表格布局虽然没有什么大的问题,但是在我们要细化结构的时候会显得很繁琐,同时表格布局三个单元格的高度会一起变动也不利于我们进行布局。
网格布局:代码优美简洁,不过还是兼容性问题。但是未来是美好的!

正文完
 0