题目: 写出三栏布局
要求: 高度已知,左右栏固定在两侧且宽度均为300px,中间栏自适应
通用样式
*{
margin:0;
padding:0;
}
.layout{
margin-bottom:20px;
}
.layout div{
min-height:100px;
}
方法一、浮动布局
/*css部分*/
/*1. 浮动布局*/
.layout.float .left{
float:left;
width:300px;
background:red;
}
.layout.float .right{
float:right;
width:300px;
background:yellow;
}
.layout.float .center{
background:green;
}
/*html部分*/
<article class="layout float">
<div class="left">左浮动</div>
<div class="right">右浮动</div>
<div class="center">
<h2>1.这是浮动布局</h2>
<p>注:center一定要放在两格浮动元素的后边,如果center放在right的后边,right会被挤到下一行</p>
</div>
</article>
局限性:浮动脱离文档流,注意清除浮动
优点:兼容性比较好
方法二、定位布局
/*css部分*/
/*2.定位布局*/
.layout.absolute{
position:relative;
}
.layout.absolute .left{
position:absolute;
left:0;
width:300px;
background:red;
}
.layout.absolute .center{
position:absolute;
left:300px;
right:300px;
background:green;
}
.layout.absolute .right{
position:absolute;
right:0;
width:300px;
background:yellow;
}
/*html部分*/
<article class="layout absolute">
<div class="left">左</div>
<div class="center">
<h2>2.这是定位布局</h2>
</div>
<div class="right">右</div>
</article>
局限性:由于脱离了文档流,导致有效性和可使用性较差
优点:快捷,不易出问题
方法三、flex布局
/*css部分*/
/*3.flex布局*/
.layout.flex{
display: flex;
margin-top:140px;
}
.layout.flex .left{
width:300px;
background:red;
}
.layout.flex .center{
flex:1;
background:green;
}
.layout.flex .right{
width:300px;
background:yellow;
}
/*html部分*/
<article class="layout flex">
<div class="left">左</div>
<div class="center">
<h2>3.这是flex布局</h2>
<p>为父元素设置display:flex;中间元素设置flex:1;两侧元素设置固定宽度</p>
</div>
<div class="right">右</div>
</article>
缺点:IE10+支持
优点:相对比较完美
方法四、表格布局
/*css部分*/
/*4.表格布局*/
.layout.table{
display: table;
width:100%;
}
.layout.table div{
display: table-cell;
height:100px;
}
.layout.table .left{
width:300px;
background:red;
}
.layout.table .center{
background:green;
}
.layout.table .right{
width:300px;
background:yellow;
}
/*html部分*/
<article class="layout table">
<div class="left">左</div>
<div class="center">
<h2>4.这是表格布局</h2>
<p>为父元素设置display:table;子元素display:table-cell;两侧元素设置固定宽度</p>
</div>
<div class="right">右</div>
</article>
缺点:其中一个单元格高度超出时,另外两个也会同时变化
优点:兼容性好
方法五、网格布局
/*css部分*/
/*5.网格布局*/
.layout.grid{
display: grid; //网格布局
width:100%;
grid-template-rows:100px; //设置高度
grid-template-columns:300px auto 300px; //设置各部分的宽度
}
.layout.grid .left{
background:red;
}
.layout.grid .center{
background:green;
}
.layout.grid .right{
background:yellow;
}
/*html部分*/
<article class="layout grid">
<div class="left">左</div>
<div class="center">
<h2>5.这是网格布局</h2>
<p></p>
</div>
<div class="right">右</div>
</article>
缺点:IE11以上支持
优点:比较好
最终实现效果如图:
注:当其中一个高度撑开时
flex布局、表格布局的另外两个div的高度也会随之撑开,依然可以使用。另外三个不可以。