在 CSS 中,可以使用以下属性来控制表格的样式和布局:
border
:设置表格边框的样式、宽度和颜色。例如:border: 1px solid #000;
表示设置表格边框为黑色实线,宽度为1像素。border-collapse
:设置表格边框的合并方式,可选值为collapse
(合并边框)和separate
(分开边框)。border-spacing
:设置表格边框之间的间距。例如:border-spacing: 5px;
表示设置表格边框之间的间距为5像素。background-color
:设置表格的背景颜色。text-align
:设置表格内容的水平对齐方式,可选值为left
、center
和right
。vertical-align
:设置表格内容的垂直对齐方式,可选值为top
、middle
和bottom
。width
和height
:设置表格的宽度和高度。例如:width: 100%; height: 200px;
表示设置表格的宽度为100%,高度为200像素。padding
:设置表格内容与表格边框之间的距离。例如:padding: 10px;
表示设置表格内容与表格边框之间的距离为10像素。font-size
:设置表格内容的字体大小。font-weight
:设置表格内容的字体粗细。在控制表格样式和布局时,可以使用以上属性进行定制化。同时,也可以通过使用 class
和 id
来对不同的表格进行不同的样式设置。例如:
/* 设置表格样式 */
.table {
border-collapse: collapse;
border-spacing: 0;
width: 100%;
background-color: #fff;
font-size: 14px;
}
/* 设置表头样式 */
.table th {
background-color: #f5f5f5;
font-weight: bold;
text-align: center;
padding: 8px;
}
/* 设置单数行的背景颜色 */
.table tr:nth-child(odd) {
background-color: #f9f9f9;
}
/* 设置偶数行的背景颜色 */
.table tr:nth-child(even) {
background-color: #fff;
}
/* 设置单元格样式 */
.table td {
border: 1px solid #ddd;
text-align: left;
padding: 8px;
}
以上代码定义了一个样式为 .table
的表格,其中表头样式为 .table th
,单数行背景颜色为 .table tr:nth-child(odd)
,偶数行背景颜色为 .table tr:nth-child(even)
,单元格样式为 .table td
。在 HTML 中使用 <table>
标签定义表格,并加上对应的 class 即可应用以上样式。