8月1日晚上做了网易的内推练习题,其中有一道题是写出两种两列布局的方案,所以考完后就搜了下,总结至少有六种。
html代码:
<div class="parent">
<div class="left">left</div>
<div class="right">right</div>
</div>
方案一:table布局
css代码:
.parent{
width: 100%;
height: 300px;
display: table;
}
.left{
width:180px;
height: 300px;
background-color: red;
display: table-cell;
}
.right{
height: 300px;
background-color: blue;
display: table-cell;
}
效果:
也可以为单元格增加间距:
.parent{
width: 100%;
height: 300px;
display: table;
border-collapse: separate;
border-spacing: 10px;
}
效果:
方案二:flex布局
(推荐阮一峰的http://www.ruanyifeng.com/blog/2015/07/flex-grammar.html)
.parent{
width: 100%;
height: 300px;
display: flex;
}
.left{
width:180px;
height: 300px;
background-color: red;
margin-right: 10px;
}
.right{
height: 300px;
background-color: blue;
flex: 1;
}
效果:
方案三:calc
这边需要改一下html代码:
<div class="parent">
<div class="left">left</div><div class="right">right</div>
</div>
区别在哪里呢?就是两个div之间没有空格也没有换行。
css代码:
.parent{
width: 100%;
height: 300px;
}
.left{
width:180px;
height: 300px;
background-color: red;
margin-right: 10px;
display: inline-block;
}
.right{
height: 300px;
background-color: blue;
width: calc(100% - 190px);
display: inline-block;
}
效果:
为什么要更改html代码呢?就是因为如果你的html中一系列元素每个元素之间都换行了,当你对这些元素设置inline-block时,这些元素之间就会出现空白。
方案四:父元素相对定位、内边距 + 子元素绝对定位 + 子元素默认
css代码:
.parent{
width: 100%;
height: 300px;
position: relative;
padding-left: 190px;
}
.left{
position: absolute;
top:0;
left: 0;
width:180px;
height: 300px;
background-color: red;
}
.right{
height: 300px;
background-color: blue;
}
效果:
方案五:父元素相对定位 + 子元素绝对定位 + 子元素外边距
css代码:
.parent{
width: 100%;
height: 300px;
position: relative;
}
.left{
position: absolute;
top:0;
left: 0;
width:180px;
height: 300px;
background-color: red;
}
.right{
margin-left: 190px;
height: 300px;
background-color: blue;
}
效果:
方案六:利用BFC
.parent{
width: 100%;
height: 300px;
}
.left{
float: left;
width:180px;
height: 300px;
background-color: red;
}
.right{
overflow: hidden;
zoom:1;
height: 300px;
background-color: blue;
}
效果: