nth-child在表格元素中不起作用。

huangapple go评论53阅读模式
英文:

nth-child does not work with table elements

问题

使用nth-child(1)在表格上时,为什么样式不仅应用于第一个单元格?

<!DOCTYPE html>
<html>
<head>
<style> 

.header:nth-child(1) {
  background: lightgreen;
}

</style>
</head>
<body>

 <table>
   <tr class="header">
     <th>Company</th>
     <th>Contact</th>
     <th>Country</th>
   </tr>
  <tr>
    <td>Alfreds Futterkiste</td>
    <td>Maria Anders</td>
    <td>Germany</td>
  </tr>
  <tr>
    <td>Centro comercial Moctezuma</td>
    <td>Francisco Chang</td>
    <td>Mexico</td>
  </tr>
</table> 

</body>
</html>
英文:

When using :nth-child(1) on a table, Why does the style not only apply to the first cell?

nth-child在表格元素中不起作用。

<!DOCTYPE html>
<html>
<head>
<style> 

.header:nth-child(1) {
  background: lightgreen;
}

</style>
</head>
<body>

 <table>
   <tr class="header">
     <th>Company</th>
     <th>Contact</th>
     <th>Country</th>
   </tr>
  <tr>
    <td>Alfreds Futterkiste</td>
    <td>Maria Anders</td>
    <td>Germany</td>
  </tr>
  <tr>
    <td>Centro comercial Moctezuma</td>
    <td>Francisco Chang</td>
    <td>Mexico</td>
  </tr>
</table> 

</body>
</html>

答案1

得分: 0

可能需要声明元素选择器来应用样式。

<style> 

.header > :nth-child(1) {
  background: lightgreen;
}

</style>
英文:

you probably need to declare the element selector for applying styles.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-html -->

&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;
&lt;style&gt; 

.header &gt; :nth-child(1) {
  background: lightgreen;
}

&lt;/style&gt;
&lt;/head&gt;
&lt;body&gt;

 &lt;table&gt;
   &lt;tr class=&quot;header&quot;&gt;
     &lt;th&gt;Company&lt;/th&gt;
     &lt;th&gt;Contact&lt;/th&gt;
     &lt;th&gt;Country&lt;/th&gt;
   &lt;/tr&gt;
  &lt;tr&gt;
    &lt;td&gt;Alfreds Futterkiste&lt;/td&gt;
    &lt;td&gt;Maria Anders&lt;/td&gt;
    &lt;td&gt;Germany&lt;/td&gt;
  &lt;/tr&gt;
  &lt;tr&gt;
    &lt;td&gt;Centro comercial Moctezuma&lt;/td&gt;
    &lt;td&gt;Francisco Chang&lt;/td&gt;
    &lt;td&gt;Mexico&lt;/td&gt;
  &lt;/tr&gt;
&lt;/table&gt; 

&lt;/body&gt;
&lt;/html&gt;

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年3月31日 17:34:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/75896932.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定