一、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/zh-hk/n/241470.html