Html CSS 选择器主表中的最后一行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16010791/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 07:33:19  来源:igfitidea点击:

CSS selector last row from main table

htmlcsscss-selectors

提问by Roh-Land

I have a table inside a table, and I want to fill the background of the last row of table 1 only — not table 2.

我在表中有一个表,我只想填充表 1 最后一行的背景,而不是表 2。

<style> 
#test tr:last-child
{
  background:#ff0000;
}
</style>

<table border="1" width="100%" id="test">
<tr>
 <td>
  <table border="1" width="100%">
   <tr>
    <td>table 2</td>
   </tr>
  </table>
 </td>
</tr> 

<tr><td>table 1</td></tr>
<tr><td>table 1</td></tr>
<tr><td>table 1</td></tr>

</table>

With my CSS, I'm coloring both last rows of table1 and table2.

使用我的 CSS,我为 table1 和 table2 的最后一行着色。

回答by CherryFlavourPez

Your tables should have as immediate children just tbodyand theadelements, with the rows within*. So, amend the HTML to be:

你的表应该有直接子元素tbodythead元素,行在*内。因此,将 HTML 修改为:

<table border="1" width="100%" id="test">
  <tbody>
    <tr>
     <td>
      <table border="1" width="100%">
        <tbody>
          <tr>
            <td>table 2</td>
          </tr>
        </tbody>
      </table>
     </td>
    </tr> 
    <tr><td>table 1</td></tr>
    <tr><td>table 1</td></tr>
    <tr><td>table 1</td></tr>
  </tbody>
</table>

Then amend your selector slightly to this:

然后将您的选择器稍微修改为:

#test > tbody > tr:last-child { background:#ff0000; }

See it in action here. That makes use of the child selector, which:

这里查看它的实际效果。这利用了子选择器,它:

...separates two selectors and matches only those elements matched by the second selector that are direct children of elements matched by the first.

...分隔两个选择器并仅匹配与第二个选择器匹配的那些元素,这些元素是与第一个选择器匹配的元素的直接子元素。

So, you are targeting only direct children of tbodyelements that are themselves direct children of your #testtable.

因此,您只针对tbody本身是#test表的直接子元素的元素的直接子元素。

Alternative solution

替代方案

The above is the neatest solution, as you don't need to over-ride any styles. The alternativewould be to stick with your current set-up, and over-ride the background style for the inner table, like this:

以上是最简洁的解决方案,因为您不需要超越任何样式。另一种方法是坚持您当前的设置,并覆盖内表的背景样式,如下所示:

#test tr:last-child { background:#ff0000; }
#test table tr:last-child { background:transparent; }

* It's not mandatory but most (all?) browsers will add these in, so it's best to make it explicit. As @BoltClock states in the comments:

* 这不是强制性的,但大多数(所有?)浏览器都会添加这些,所以最好让它明确。正如@BoltClock 在评论中所述:

...it's now set in stone in HTML5, so for a browser to be compliant it basically must behave this way.

...它现在在 HTML5 中是一成不变的,因此要使浏览器兼容,它基本上必须以这种方式运行。