一、display table-cell
在使用CSS书写页面布局时,难免会遭遇到居中或者平均分配子元素宽度等问题。此时,我们可以通过设置display: table-cell来解决,这会使当前元素表现得像一个表格单元元素一样,其宽度由内部元素决定,而不是由自身决定。
另外,在display: table-cell下,我们可以使用vertical-align属性来控制内部元素的垂直对齐方式,以实现纵向居中、底部对齐等效果。
.container {
display: table;
width: 100%;
}
.child {
display: table-cell;
text-align: center;
vertical-align: middle;
}
二、display table 合并单元格
CSS的display属性还支持table、table-row和table-cell等值,表现得像一个表格结构一样。使用display: table结合table-row和table-cell等值,我们可以轻松实现合并表格单元格的效果。
.container {
display: table;
width: 300px;
border-collapse: collapse;
}
.row {
display: table-row;
}
.cell {
display: table-cell;
border: 1px solid black;
}
.colspan {
display: table-cell;
border: 1px solid black;
}
.colspan span {
display: none;
}
.colspan:nth-child(2) {
position: relative;
}
.colspan:nth-child(2) span {
display: block;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
三、display table cell垂直居中
在表格中实现表格行或表格单元格内的元素垂直居中时,会遇到一些兼容性问题。在不使用table布局的情况下,我们可以使用CSS3弹性盒模型display: flex,或者使用position: absolute,top: 50%,transform: translateY(-50%)的方案实现垂直居中。
.container {
display: table;
width: 300px;
height: 200px;
border-collapse: collapse;
}
.row {
display: table-row;
}
.cell {
display: table-cell;
height: 50%;
vertical-align: middle;
text-align: center;
border: 1px solid black;
position: relative;
}
.cell:before {
content: "";
height: 100%;
vertical-align: middle;
display: inline-block;
visibility: hidden;
}
.content {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
四、display显示表格
display: table和display: table-cell实现了表格结构的一些特性,但是默认情况下不会有表格的渲染效果,如果需要表格外观,需要设置border样式。
.container {
display: table;
width: 100%;
border-collapse: collapse;
border: 2px solid black;
}
.row {
display: table-row;
}
.cell {
display: table-cell;
text-align: center;
border: 1px solid black;
}
五、display显示为表格单元格
有时候我们需要实现类似于表格的效果,但是又不想使用table布局,这时候我们可以使用display: inline-block和display: block实现网格布局,同时使用伪元素:after清除浮动,使得每一行元素能够横向排列,每个元素能够自适应宽度,并且实现像表格单元格一样的边框效果。
.container {
margin: 0 auto;
overflow: hidden;
}
.cell {
display: inline-block;
width: 25%;
padding: 10px;
box-sizing: border-box;
border: 1px solid black;
float: left;
position: relative;
}
.cell:before,
.cell:after {
content: "";
display: table;
border-collapse: collapse;
}
.cell:after {
clear: both;
}
原创文章,作者:小蓝,如若转载,请注明出处:https://www.506064.com/n/241470.html
微信扫一扫
支付宝扫一扫