记载几种常见的 多列布局方案 ,比较基础 不做解释 看不懂的可以参考文档属性
定宽+自适应
html结构 左侧定宽右侧自适应
消除默认padding,margin并且给左右p标签设置眼色以便区分
<div class="parent">
<div class="left">
<p>left</p>
</div>
<div class="right">
<p>right</p>
<p>right</p>
</div>
</div>
<style type="text/css">
*{padding: 0;margin: 0;}
p{
background: #666;
}
.right p{
background: #999;
}
</style>
1. float+margin
.left{ float: left;width: 100px}
.right{ margin-left: 120px;}
2. float+overflow
.left{float: left;width: 100px;margin-right:20px;}
.right{overflow: hidden;}
3.table
.parent{display: table;width: 100%;table-layout: fixed;}
.left,.right{display: table-cell;}
.left{width: 100px;padding-right: 20px;}
4.flex
.parent{display: flex;}
.left{width: 100px;margin-right: 20px;}
.right{flex: 1;}
上面几种方案 也可以解决 多列定宽 +自适应
不定宽 + 自适应
容器不固定宽度 根据内容自适应宽度
html结构延用上面内容 只需要修改css
1. float+overflow
.left{float: left;margin-right:20px;}
.left p{widht:100px;}
.right{overflow: hidden;}
2.table
.parent{display: table;width: 100%;}
.left,.right{display: table-cell;}
.left{width: 1px;padding-left:20px;}
因为没有设置table-layout: fixed; 里面元素不会是等宽 根据内容长度决定宽度
设置left 1px,里面内容会自动撑开left,table-layout: fixed;没有设置所以内容优先。
3.flex 根据left中p撑开父元素
.parent{display: flex;}
.left{margin-right: 20px;}
.right{flex: 1;}
.left p{width:100px;}
等宽布局
html结构
<div class="box">
<div class="parent">
<div class="child"><p>1</p></div>
<div class="child"><p>1</p></div>
<div class="child"><p>1</p></div>
<div class="child"><p>1</p></div>
</div>
</div>
1.float 解决等宽多列布局方案
看见上面这种html结构肯定第一时间想到的是 child宽度25% 在加个浮动 ok是可以解决等分;那如果每一列中间有间距的时候 算起来是不是很麻烦。 看下图和公式就会得出一个很简单的方案。
.box{width: 400px;height: 100px;margin: 0 auto;overflow: hidden;}
.parent{width: 400px;height: 100px;background: #ccc;margin-left: -10px;}
.child{width: 25%;text-align: center;float: left;padding-left: 10px;
box-sizing:border-box;height: 100px;}
child p{background: red;height: 100px;}
假设child间距是10px的话 让parent元素向左伸展出去一个10px 设置child百分之25;每个元素加上padding-left 10px;
最重要的是设置box-sizing:border-box属性; 由此可以得出上面图的效果, 给parent父级加overflow: hidden;就实现等分效果了。
2.flex方案
flex方案比较简单
.box{width: 400px;height: 100px;margin: 0 auto;overflow: hidden;}
.parent{display: flex;}
.child{flex: 1;text-align: center;}
/* +号是css兄弟选择器*/
.child+.child{margin-left: 10px;}
.child p{background: red;height: 100px;}
等高布局
html结构
<div class="parent">
<div class="left">
<p>left</p>
</div>
<div class="right">
<p>right</p>
<p>right</p>
<p>right</p>
</div>
</div>
1.flex方案
.parent{display: flex;}
.left{width: 100px;margin-right: 20px;}
.right{flex:1;}
2.table
.parent{display: table;width:100%;table-layout: fixed;}
.left,.right{display: table-cell;}
.left{width: 100px;border-right: 20px solid transparent;
background-clip: padding-box;}