定义:table-cell 此元素会作为一个表格单元格显示(类似 td 和 th)
兼容性:
在项目过程中有时候会需要父元素高度随着子元素高度变化而变化,但是子元素中又不是高度全部都是固定的,高度是随着内容改变而自适应的,于是就出现了display:tabel-cell。
用过table的都知道,table中的td属性高度是随着子元素的高度变化而变化,同一个tr里面的所有td高度都是一样的,这就是table-cell。话不多说了。看码。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>display:tabel-cell实现多列等高</title>
<style>
#od .item{display:table-cell;background:#ccc;color:#fff;font-size:18px;}
#od .box01{height:100px;width:400px;background:red;}
#od .box02{height:200px;width:300px;background:blue;}
#od .box03{height:300px;width:300px;background:yellow;}
#od .box04{height:400px;width:300px;background:green;}
</style>
<body>
<div class="ob" id="od">
<div class="item">
<div class="box01">
Height:100px;
</div>
</div>
<div class="item">
<div class="box02">
Height:200px;
</div>
</div>
<div class="item">
<div class="box03">
Height:300px;
</div>
</div>
<div class="item">
<div class="box04">
Height:400px;
</div>
</div>
</div>
</body>
</html>
</head>
结果:
从结果上看,样式里面并没有设置item的高度,但是每个item的高度就是一样的高度,都是height:400px;子元素中最大的适应高度。这样就可以实现多列等高布局了。
另外tabel-cell还可以实现不固定高度水平垂直居中效果。
如图所示
item值并没有设置高度,也没有设置margin:0 auto;常用的水平居中效果,但是他依然可以实现水平垂直居中。
代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>display:tabel-cell水平垂直居中</title>
<style>
#od .item{height:200px;width:200px;display:table-cell;vertical-align:middle;text-align:center;background:#ccc;color:#fff;font-size:18px;}
#od .box01{display:inline-block;width:150px;background:red;}
</style>
<body>
<div class="ob" id="od">
<div class="item">
<div class="box01">
<div style="height:60px;">
</div>
</div>
</div>
</body>
</html>
</head>
结束语:太热了,没有空调吹,只能先这样了。。。。。