CSS not select无法使用子字符串选择器



我在一个表中有几个<th>标记,我想更改它们的颜色,除非是第一个。我尝试了css :not选择器,但当把子字符串选择器放在里面时,它不起作用。只有当我直接放置元素的id时,它才起作用。然而,我想让它更具动态性(例如,不需要每次都更改id)。我该怎么做?

//This is not working
th[id*="header"]:not(th[id*="header0"])
//This is working
th[id*="header"]:not(#header0)

/*
th[id*="header"]:not(th[id*="header0"]) {
  color: red;
}
*/
th[id*="header"]:not(#header0) {
  color: red;
}
<table>
  <tr>
    <th id="header0">Header0</th>
    <th id="header1">Header2</th>
    <th id="header2">Header3</th>
    <th id="header3">Header4</th>
    <th id="header4">Header5</th>
    <th id="header5">Header6</th>
  </tr>
</table>

与其尝试各种方法,为什么不使用下面这样的简单方法呢?

th{
  color: red;
}
th:first-child{
  color: black;
}

哪个比这样使用更兼容:

th:not(:first-child) {
   color: red;
}

回答您的问题:

//This is not working
th[id*="header"]:not(th[id*="header0"])

因为th[id*="header"]选择id为的所有第th个元素,并且在任何位置都有标题字符串,并且使用not选择器意味着使用:not(th[id*="header0"])将选择th[id*="header"]的子元素,而您没有该子元素,即第个。即使是:not选择器也不能用于复杂的选择器。请参阅此参考以查看简单选择器。

//This is working
th[id*="header"]:not(#header0)

这之所以有效,是因为它表明您没有选择同一标头th[id*="header"] 的第9个CCD_元素

I怀疑您正在寻找类似的东西

th[id^="header"]:not([id$="0"]) {
  color: red;
}
<table>
  <tr>
    <th id="header0">Header0</th>
    <th id="header1">Header2</th>
    <th id="header2">Header3</th>
    <th id="header3">Header4</th>
    <th id="header4">Header5</th>
    <th id="header5">Header6</th>
  </tr>
</table>

其中th[id^="header"]:not([id$="0"])读作:

ID从"header"开始但不以"0"结束的任何th元素。

您可以使用不带的第一个子选择器

th:not(:first-child) {
    color: red;
}

最新更新