知识梳理
display:table
display:table-cell,相当于td元素
display:table-row,相当于tr元素
table-layout:fixed | auto(默认)
table-layout 属性用于显示表格单元格、行、列的算法规则
auto, 自动表格布局,列的宽度由单元格中最大 内容的宽度决定,算法 较慢 (在确定最终布局之前要访问表格中所有内容)
fixed ,固定表格布局,接收第一行就可以显示表格,与表格内容无关,允许浏览器 更快 的对表格进行布局
table
table可设置宽高,margin、border、padding属性
table宽高默认由内容撑开。
若设置了宽度,宽度默认由里面的td平分。
若给定了某个td的宽度,剩余宽度被其他td平分
table设置高度只起到min-height的作用。
当内容的高度高于设置的高度时,table的高度会被撑高
tr
tr设置的高度只起到min-height的作用,默认会平分table的高度
设置宽度、margin都不起作用
td
td会默认继承tr的高度,且平分table的宽度
给任意td设置了高度,其他td的高度也同样变高,适合多列等高布局
若为设置display:table,则td设置的宽高不能用百分比只能用准确的数值
td设置vertical-align:middle,td元素的所有(除float/position)块级非块级元素都会相对于td垂直居中
td设置text-align:center,td元素的所有非block元素(除float/position)都会相对于td水平居中,block元素虽不居中,但其中的文字或inline元素会水平居中
table为何被摒弃
非语义化、布局代码冗余,以及不好维护改版
表格渲染时导致页面重绘带来的性能问题
现在的css吸取了table布局好的特性模拟table布局
案例
1.对于不定宽高的div或元素水平垂直居中
.box{
width: 400px;
height: 400px;
display: table-cell;
text-align: center;
vertical-align: middle;
border: 1px solid #ccc;
}
<div class="box">
<img src="./img/flower.jpg" />
</div>
2.浮动元素水平垂直居中
.box{
width: 200px;
height: 200px;
display: table-cell;
vertical-align: middle;
text-align: center;
border: 1px solid red;
}
.box-float{
width: 80px;
height: 80px;
line-height: 80px;
border: 1px solid #ccc;
}
.box-left{
float: left;
}
.box-right{
float:right;
}
<div class="box">
<div class="box-float box-left">左</div>
<div class="box-float box-right">右</div>
</div>
3.等高布局
.box{
display: table;
min-height: 50px;
border: 1px solid red;
}
.item{
width: 50px;
border: 1px solid #ccc;
display: table-cell;
}
<div class="box">
<div class="item">
<h2>item1</h2>
<h2>item1</h2>
<h2>item1</h2>
</div>
<div class="item">item2</div>
<div class="item">item3</div>
<div class="item">item4</div>
<div class="item">item5</div>
</div>
4.固定宽度剩余自适应布局
.layout.table article{
display: table;
min-height: 100px;
}
.layout.table .left{
width: 300px;
background: blue;
display: table-cell;
}
.layout.table .right{
width: 300px;
background: red;
display: table-cell;
}
.layout.table .center{
background: yellow;
display: table-cell;
}
<article class="left-right-center">
<div class="left"></div>
<div class="center">
<h1>css布局table解决方案</h1>
<h1>css布局table解决方案</h1>
<h1>css布局table解决方案</h1>
<h1>css布局table解决方案</h1>
<h1>css布局table解决方案</h1>
<h1>css布局table解决方案</h1>
</div>
<div class="right"></div>
</article>