CSS 在一个选择器中选择除第一个和最后一个 td 元素之外的所有元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13319334/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Select all except first and last td element in one selector
提问by Kamil
I wrote something like this in CSS:
我在 CSS 中写了这样的东西:
tr.red > td:not(:last-of-type):not(:first-of-type)
{
color: #E53B2C;
border-bottom: 4px solid #E53B2C;
}
I'm trying to apply this to table cells, which are not first and not last in the row with .red
class.
我正在尝试将其应用于表格单元格,这些表格单元格不是第一个也不是最后一个在.red
类的行中。
It seems to work as expected, but is this really the right way to do it?
它似乎按预期工作,但这真的是正确的方法吗?
采纳答案by Jukka K. Korpela
It is syntactically correct, as you can quickly check using the W3C CSS Validator. The validator is known to have errors, so in principle, you should check the rule against CSS specifications, especially Selectors Level 3. The result is still that yes, it is correct.
它在语法上是正确的,因为您可以使用W3C CSS Validator快速检查。已知验证器有错误,因此原则上,您应该根据 CSS 规范检查规则,尤其是Selectors Level 3。结果仍然是是的,它是正确的。
It also has the desired meaning, since this is how selectors combine. You can use :not(...)
selectors to express a condition of type “not ... and not ...”.
它也具有所需的含义,因为这就是选择器的组合方式。您可以使用:not(...)
选择器来表达“not ... and not ...”类型的条件。
This applies provided that all children of tr
elements are td
. If there are header cells, i.e. th
elements as well, then the selector applies to those data cells (td
elements) that are not the first data cell or the last data cell in a row with .red
class.
如果tr
元素的所有子元素都是td
. 如果有标题单元格,即th
元素,则选择器应用于那些td
不是第一个数据单元格或具有.red
类的行中的最后一个数据单元格的数据单元格(元素)。
回答by Priyank Patel
回答by Vlasec
As some told, td:first-of-type gives you first TD, where td:first-child selects the first child element of that tR if it's TD. This means, your code won't give you all the cells that aren't first or last if you have any TH.
正如某些人所说, td:first-of-type 为您提供第一个 TD,其中 td:first-child 选择该 tR 的第一个子元素(如果它是 TD)。这意味着,如果您有任何 TH,您的代码不会为您提供所有不是第一个或最后一个的单元格。
tr.red > *:not(:last-child):not(:first-child)
{ /* ... your css code ... */ }
I think it should work well this way. Even if you wanted to have separate code for TH and TD, you could do it like th:not(:first-child) and td:not(:first-child). Your code would be better when you want to find first element with some tag name, like p:first-of-type and give it some different style.
我认为它应该以这种方式运作良好。即使你想为 TH 和 TD 分别编写代码,你也可以像 th:not(:first-child) 和 td:not(:first-child) 那样做。当您想找到具有某个标记名称的第一个元素(例如 p:first-of-type)并为其赋予一些不同的样式时,您的代码会更好。