★★★ float(+margin)浮动布局 ★★★
(均以三栏布局为例,中间宽度自适应)
实现: 利用浮动,(margin属性腾出其他块的空间)
<style>
body, .container{
margin: 0;
padding: 0;
height: 300px;
}
.left{
float: left;
width: 200px;
height: 100%;
background: red;
}
.main{
height: 100%;
background: pink;
margin: 0 200px; /*中间用margin空出左右元素所占的空间*/
}
.right{
float: right;
width: 200px;
height: 100%;
background: green;
}
.text-midle{
line-height: 300px;
} /*使用line-height=height使文字居中,注意不能用vertical,因为这是文本对齐方式,
只对行,行内块元素有效,对块级元素无效*/
</style>
</head>
<body>
<div class="container">
<div class="left text-midle">左</div>
<div class="right text-midle">右</div>
<div class="main text-midle">中</div>
//右栏要放在中栏前面,这是因为上面没给中栏设置浮动,浮动没脱离文本流,所以中栏有文字会把
浮动的元素顶走。position布局也是这。也都可以选择给中栏设置浮动/绝对定位来消除。position
布局也可以用top:0,消除被顶走的区域。
</div>
优点:快捷 简单 兼容性较好
缺点:有局限性 脱离文档流 需要清除浮动等
★★★ flex弹性布局 ★★★
阮一峰flex语法篇
阮一峰flex实例篇
优点:比较完美 移动端首选
缺点:不兼容 ie9 及以下
★★★ position绝对定位布局 ★★★
实现:利用position:absolute;绝对定位脱离文档流,使用位置属性(left,top,right,bottom)进行布局。在调整位置的时候,左右和上下位置属性都要定义,以免出现位置错误。
<style>
.container{
height: 300px;
position: relative;
background-color: gray;
}
.main{
margin: 0 200px;
}
.left, .right{
position: absolute;
height: 100%;
top: 0;
}
.left{
left: 0;
width: 200px;
background: red;
}
.right{
right: 0;
width: 200px;
background:pink;
}
</style>
</head>
<body>
<div class="container">
<div class="left text-midle">左</div>
<div class="main text-midle">中</div>
<div class="right text-midle">右</div> //这里也要注意,可能会被中栏文本顶走,
要设置top:0,或者给中栏也设置绝对定位
</div>
优点:很简单
缺点:脱离文档流 高度未知会出现坍塌 可用性差
★★★ table表格布局 ★★★
<style>
table{
width: 100%; /*这里设置了100%后,左右固定后,中间就可以自适应了*/
height: 300px;
border-collapse: collapse; /*消除边框*/
}
.left{
width: 200px;
background: red;
}
.main{
background: pink;
}
.right{
width: 200px;
background: gray;
}
</style>
</head>
<body>
<table>
<tr>
<td class="left">左</td>
<td class="main">中</td>
<td class="right">右</td>
</tr>
</table>
优点:兼容性很好(ie8 及以上) 父元素高度会被子元素撑开(不担心高度塌陷)
缺点:seo 不友好,当其中一个单元格高度超出的时候,其他的单元格也是会跟着一起变高的
★★★ inline-block布局 ★★★
消除inline-blick 布局间隙 : 给父元素设置 字体为哦 font-size:0 子元素内重新设置字体大小。
table间隙是 单元格的边框 ,给table设置border-collapse: collapse;就行