首页 > 解决方案 > 已经使用 :nth-child 时,将 CSS 样式应用于类型的第一个元素

问题描述

在下面的示例中,我不想对单元格应用任何背景颜色Not here...

换句话说,我只想将我的 CSS 应用于.class tag:modifertype 的第一个子元素tag

.foo {
border-collapse: collapse;
}

.foo tr:nth-child(1) td:nth-child(1) {
background-color: green;
}

.foo tr:nth-child(2) td:nth-child(2) {
background-color: red;
}
<table class="foo">
  <tr><td>A</td><td>B</td></tr>
  <tr><td>C</td>
  <td>
     <table><tr><td>Not here...</td></tr></table>
  </td>
  </tr>
</div>

标签: htmlcsscss-selectors

解决方案


  1. 使用直接后代组合器 >
  2. 找到树上更高的祖先<div>
  3. 采用nth-of-type
div > table > tbody > tr:first-of-type > td:first-of-type 

.foo {
  border-collapse: collapse;
}

div>table>tbody>tr:first-of-type>td:first-of-type {
  background-color: green;
}

.foo tr:nth-child(2) td:nth-child(2) {
  background-color: red;
}
<div>
  <table class="foo">
    <tr>
      <td>A</td>
      <td>B</td>
    </tr>
    <tr>
      <td>C</td>
      <td>
        <table>
          <tr>
            <td>Not here...</td>
          </tr>
        </table>
      </td>
    </tr>
  </table>
</div>


推荐阅读