CSS表模型基于HTML表模型
一个表分为ROWS,并且每一行包含一个或多个单元格。单元格是ROWS的子级,它们是列的子级。
“ display:table-column”不提供用于制作列式布局的机制(例如,具有多列的报纸页面,其中内容可以从一列流向下一列)。
而是,“表列”仅设置应用于表行中相应单元格的属性。例如,可以描述“每行中第一个单元格的背景颜色是绿色”。
该表本身的结构始终与HTML中的结构相同。
在HTML中(请注意,“ td”位于“ tr”内部,而不位于“ col”内部):
<table ..>
<col .. />
<col .. />
<tr ..>
<td ..></td>
<td ..></td>
</tr>
<tr ..>
<td ..></td>
<td ..></td>
</tr>
</table>
使用CSS表属性的相应HTML(请注意,“ column” div不包含任何内容,该标准不允许直接在列中包含内容):
.mytable {
display: table;
}
.myrow {
display: table-row;
}
.mycell {
display: table-cell;
}
.column1 {
display: table-column;
background-color: green;
}
.column2 {
display: table-column;
}
<div class="mytable">
<div class="column1"></div>
<div class="column2"></div>
<div class="myrow">
<div class="mycell">contents of first cell in row 1</div>
<div class="mycell">contents of second cell in row 1</div>
</div>
<div class="myrow">
<div class="mycell">contents of first cell in row 2</div>
<div class="mycell">contents of second cell in row 2</div>
</div>
</div>
:可以通过如下方式为每行和每个单元格分配多个类来设置“行”和“列”的样式。这种方法在指定要设置样式的各种单元格或单个单元格时提供了最大的灵活性:
//Useful css declarations, depending on what you want to affect, include:
/* all cells (that have "class=mycell") */
.mycell {
}
/* class row1, wherever it is used */
.row1 {
}
/* all the cells of row1 (if you've put "class=mycell" on each cell) */
.row1 .mycell {
}
/* cell1 of row1 */
.row1 .cell1 {
}
/* cell1 of all rows */
.cell1 {
}
/* row1 inside class mytable (so can have different tables with different styles) */
.mytable .row1 {
}
/* all the cells of row1 of a mytable */
.mytable .row1 .mycell {
}
/* cell1 of row1 of a mytable */
.mytable .row1 .cell1 {
}
/* cell1 of all rows of a mytable */
.mytable .cell1 {
}
<div class="mytable">
<div class="column1"></div>
<div class="column2"></div>
<div class="myrow row1">
<div class="mycell cell1">contents of first cell in row 1</div>
<div class="mycell cell2">contents of second cell in row 1</div>
</div>
<div class="myrow row2">
<div class="mycell cell1">contents of first cell in row 2</div>
<div class="mycell cell2">contents of second cell in row 2</div>
</div>
</div>
在当今<div>
有多种用途的灵活设计中,明智的做法是在每个div上放置 一个 类,以帮助引用它。在这里,曾经<tr>
在HTML中的内容变成了class myrow
,并且<td>
变成了class mycell
。这个约定使上面的CSS选择器有用。
:将类名放在每个单元格上,并使用上面的多类选择器,比使用以结尾的选择器*
(例如.row1 *
或甚至)要好.row1 > *
。原因是选择器 匹配,所以在寻找匹配元素时,.row1 *
首先*
匹配 元素,然后检查 ,以查找是否有祖先class row1
。在速度较慢的设备上的复杂文档中,这可能会很慢。.row1 > *
更好,因为只检查直系父母。但是,最好还是立即通过消除大多数元素.row1 .cell1
。(.row1 > .cell1
是一个更加严格的规范,但这是搜索的第一步,它会带来最大的不同,因此通常不值得一团糟,而且,对于是否将始终是直接子对象,需要进行额外的思考过程子选择器>
。)
取消重新 的关键是选择器中的 一项应该 ,而绝不能如此*
。