問題描述
我有以下程式碼:
<div class="table">
<div class="row">
<div class="cell">Cell</div>
<div class="cell">Cell</div>
</div>
<div class="row">
<div class="cell colspan2">Cell</div>
</div>
</div>
<style>
.table {
display: table;
}
.row {
display: table-row;
}
.cell {
display: table-cell;
}
.colspan2 {
/* What to do here? */
}
</style>
很簡單如何使用 display: table-cell 為元素新增 colspan(或相當於 colspan)?
最佳解決方案
據我所知,缺少 colspan /rowspan 只是 display:table 的侷限性之一。看到這個帖子
http://www.onenaught.com/posts/201/use-css-displaytable-for-layout
次佳解決方案
由於 OP 沒有明確規定該解決方案必須是純 CSS,所以我會固執地扔在我今天想到的解決方法中,特別是因為它比表格中的表更加優雅。
示例等於< table> 每行和兩行有兩個單元格,第二行中的單元格與 colspan = “2” 是一個 td 。
我已經用 Iceweasel 20,Firefox 23 和 IE 10 進行了測試。
CSS:
div.table
{
display:table;
width:100px;
background-color:lightblue;
border-collapse:collapse;
border:1px solid red;
}
div.row
{
display:table-row;
}
div.cell
{
display:table-cell;
border:1px solid red;
}
div.colspan,div.colspan+div.cell
{
border:0;
}
div.colspan>div
{
width:1px;
}
div.colspan>div>div
{
position:relative;
width:99px;
overflow:hidden;
}
HTML:
<div class="table">
<div class="row">
<div class="cell">cell 1</div>
<div class="cell">cell 2</div>
</div>
<div class="row">
<div class="cell colspan">
<div><div>
cell 3
</div></div>
</div>
<div class="cell"></div>
</div>
</div>
即時動作 (演示)here 。
編輯:我將程式碼更改為 printer-friendly,預設情況下離開 background-colors 。我也創造了 rowspan-demo,靈感來自遲到的答案。
第三種解決方案
一種在 Chrome 30 中適用於我的更簡單的解決方案:
Colspan 可以使用 display: table 而不是 display: table-row 進行模擬:
.table {
display: block;
}
.row {
display: table;
width: 100%;
}
.cell {
display: table-cell;
}
.row.colspan2 {/* You'll have to add the 'colspan2' class to the row, and remove the unused <div class=cell> inside it */
display: block;
}
唯一的缺陷是,堆疊行的單元格不會垂直對齊,因為它們來自不同的表。
第四種方案
只需使用 table 。
當用於佈局時,桌子只會皺起眉頭。
這似乎是表格資料 (行/列的資料) 。因此,我建議使用 table 。
有關更多資訊,請參閱 this question 的答案:
creating the same thing with divs as tables
參考文獻
注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。