使用 css 隐藏 <th> 个元素,第一个元素除外

using css to hide <th> elements except the first one

with CSS,我想隐藏除第一个元素之外的所有 TH 元素,我有这样的格式:

<table>
  <tbody>
    <tr>
      <th></th>
    </tr>
    <tr>
      <td></td>
    </tr>
    <tr>
      <td></td>
    </tr>
    <tr>
      <td></td>
    </tr>
    <tr>
      <td></td>
    </tr>
    <tr>
      <td></td>
    </tr>
    <tr>
      <td></td>
    </tr>
  </tbody>
</table>
<table>
  <tbody>
    <tr>
      <th></th>
    </tr>
    <tr>
      <td></td>
    </tr>
    <tr>
      <td></td>
    </tr>
    <tr>
      <td></td>
    </tr>
    <tr>
      <td></td>
    </tr>
    <tr>
      <td></td>
    </tr>
    <tr>
      <td></td>
    </tr>
  </tbody>
</table>
<table>
  <tbody>
    <tr>
      <th></th>
    </tr>
    <tr>
      <td></td>
    </tr>
    <tr>
      <td></td>
    </tr>
    <tr>
      <td></td>
    </tr>
    <tr>
      <td></td>
    </tr>
    <tr>
      <td></td>
    </tr>
    <tr>
      <td></td>
    </tr>
  </tbody>
</table>

我也需要检查 IE8 的解决方案,因为我知道它们不支持伪元素,我正在尝试这样

th:not(:first-child):display:none;

但这不适用于任何浏览器

first-child不是伪元素,是伪class。在任何情况下,:not 只接受一个 "simple selector"; first-child 不合格。但是在这里你不能使用 first-child ,因为它适用于具有共同父元素的元素。

在这种情况下,您可能想隐藏不在第一个 table 中的 th。所以

th                   { display: none;  }
table:first-child th { display: block; }

这是在"apply a value of X1 to some property for all Y, except in case Z apply value X2"的情况下使用的标准CSS成语。在普通的编程语言中,可能会使用包含 not 运算符的 if 语句。在CSS中,利用规则顺序的原则,你这样写:

Y { property: X1; }    // standard behavior comes first
Z ( property: X2; }    // exceptional behavior comes next

在你的情况下,"standard behavior" 是隐藏 th,而 "exceptional behavior" 是显示第一个。

您可以在这种情况下使用 :not,但它并不总是如您所愿,尤其是与其他选择器(包括其他 :not 结合使用时,更不用说 "simple selector"限制。

使用jquery你可以像

一样轻松做到

$( "th:not(:first)" ).css( "background", "green" );

$( "th:not(:first)" ).css( "background", "green" );

// "th:not(:first)" ).css( "display", "none" );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<table border="1">
  <tbody>
    <tr>
      <th>Heading</th>
    </tr>
    <tr>
      <td>sample</td>
    </tr>
    <tr>
      <td>sample</td>
    </tr>
    <tr>
      <td>sample</td>
    </tr>
    <tr>
      <td>sample</td>
    </tr>
    <tr>
      <td>sample</td>
    </tr>
    <tr>
      <td>sample</td>
    </tr>
  </tbody>
</table>
<table border="1">
  <tbody>
    <tr>
      <th>Heading</th>
    </tr>
    <tr>
      <td>sample</td>
    </tr>
    <tr>
      <td></td>
    </tr>
    <tr>
      <td>sample</td>
    </tr>
    <tr>
      <td>sample</td>
    </tr>
    <tr>
      <td>sample</td>
    </tr>
    <tr>
      <td>sample</td>
    </tr>
  </tbody>
</table>
<table border="1">
  <tbody>
    <tr>
      <th>Heading</th>
    </tr>
    <tr>
      <td>sample</td>
    </tr>
    <tr>
      <td>sample</td>
    </tr>
    <tr>
      <td>sample</td>
    </tr>
    <tr>
      <td></td>
    </tr>
    <tr>
      <td>sample</td>
    </tr>
    <tr>
      <td>sample</td>
    </tr>
  </tbody>
</table>