对th的后代不应用包裹

问题描述 投票:2回答:1

我有一个默认的white-space : normal表,并希望将white-space: nowrap应用于链接到特定th的所有td元素,但不必将其应用于<td>元素本身,而是使用外部css文件。

在下面的示例中,我只想要id为'my_code'的列具有nowrap。

<tr>
 <th id="my_code">Code</th>
 <th id="my_name">Name</th>
</tr>
<tr>
 <td>1</td>
 <td>Your name</td>
</tr>
<tr>
 <td>2</td>
 <td>Other name</td>
</tr>

我试过这个:

#my_code {
    white-space: nowrap !important;
}

和这个 :

#my_code td {
    white-space: nowrap !important;
}

但是行不通。

html css html-table
1个回答
2
投票

您不能将CSS选择器定位到td,它与class或id在th的同一列中,因为它们没有直接关系。但在上面的示例中,您可以申请:

td:nth-child(1) {
  white-space: nowrap;
}

或者,使用选择器td:first-of-type,或td:first-child ...

一般来说,另一种方法是使用<col>元素。

<table>
  <colgroup>
    <col class="class1">
    <col class="class2">
  </colgroup>
  <tr>
    ...

.class1 { /* your style */ }

这将CSS应用于整个列。但允许的风格非常有限,据我所知,只允许这些background-colorborderwidthvisibility属性。

更新

使用CSS选择器级别4,您将能够使用表伪进行:

15.1. Column combinator (||)

列组合器由两个管道(||)组成,表示列元素与属于它所代表的列的单元格元素的关系。

<table>
  <colgroup>
    <col class="class1">
    <col class="class2">
  </colgroup>
  <tr>
    ...

.class1 || td {
  /* your style */
}

在撰写本文时,任何浏览器都不支持此选择器。

© www.soinside.com 2019 - 2024. All rights reserved.