css技巧之多列等高

317 阅读1分钟

说明

这里的多列等高,是指列高由内容决定,所以是不确定的

1. padding和margin正负相抵

利用padding-bottom|margin-bottom正负值相抵

//html
<div class="container">
    <div class="left">
    	我是left
    </div>
    <div class="right">
    	我是right<br>现在我的高度比left高,
    	但left用它的padding-bottom补偿了这部分高度
    </div>
    <div style="clear:both"></div>
</div>

//css
.container{ 
    margin:0 auto; 
    width:600px; 
    border:3px solid #00C;
    overflow:hidden; //这个不能少
}
.left{ 
    float:left; 
    width:150px; 
    background:#B0B0B0;
    padding-bottom:2000px;
    margin-bottom:-2000px;
}
.right{ 
    float:left; 
    width:450px; 
    background:#6CC;
    padding-bottom:2000px;
    margin-bottom:-2000px;
}

2. flex布局

//html同上
<div class="container">
	<div class="left">
	我是left
    </div>
    <div class="right">
    	我是right<br>现在我的高度比left高,
    	但left用它的padding-bottom补偿了这部分高度
    </div>
</div>
//css
.container{ 
	margin:0 auto; 
	width:600px; 
	border:3px solid #00C;
    display: flex;
    align-items: stretch;
}
.left{
 	width:150px; 
 	background:#B0B0B0;
}
.right{ 
	width:450px; 
	background:#6CC;
}

align-items: stretch;若未指定高度,则子容器占满父容器高度