表多列宽度

Ano*_*ous 5 html css html-table

这是代码:

<table>
<col style="width:10px"><col style="width:20px"><col style="width:30px">
<td>
....
Run Code Online (Sandbox Code Playgroud)

它定义了三列不同宽度的列.有没有办法为整个表定义CSS布局 - 所有3列 - 在一个单独的条目中,以便我可以写:

<table class="cols3">
...
Run Code Online (Sandbox Code Playgroud)

这个cols3类定义这个表有3列预定义的宽度?

Jna*_*zia 8

您可以nth-child在子列上使用选择器,因此您的css可能如下所示:

.cols3 col:nth-child(1){width:10px;}
.cols3 col:nth-child(2){width:20px;}
.cols3 col:nth-child(3){width:30px;}
Run Code Online (Sandbox Code Playgroud)

请注意,使用nth-child选择器,1用于获取第一个子元素,而不是典型的0.

  • 一个小技巧:除非你在html中明确定义了3个<col>项,否则你的代码将无效.我做得更容易 - 删除了<col>项目,只写了"td:nth-​​child: (5认同)