CSS选择器span:first-child问题

12
我有一个 div。在这个 div 中,我有一个带有 2 行的表。在第二行中,我只有一个 td。在这个 td 中,我首先有一个 img,然后是一个 span,再一个 span,最后是另一个 img。我想通过 CSS 选择器选中第一个 span 并将其设置为红色。以下是我的代码。不幸的是它没有起作用。希望有人可以帮忙。提前感谢您的回复。祝好。顺便说一下,HTML 结构可能看起来很蠢。我同意。我只是简化了一下以方便阅读。所以不需要评论代码。 http://cssdesk.com/sVKXg
<div id="myDiv">
  <table cellspacing="0">

        <tr>
            <td>
                <span>Some text</span>
            </td>
        </tr>

        <tr>
            <td>
                <img src="img/quotes-open.png" alt="" />
                <span>span1</span>
                <span>span2</span>
                <img src="img/quotes-close.png" alt="" />
            </td>
        </tr>

  </table>   
</div>
#myDiv tr:nth-child(2) span:first-child{
  color:red;}
2个回答

33

:first-child选择器仅仅在它是父元素的第一个子元素时才会选择该元素。在这种情况下,第一个子元素是一个图片,而不是一个span元素。你需要使用:first-of-type选择器。

#myDiv tr:nth-child(2) span:first-of-type { color:red }

2
CSS应该是:

CSS应该是:

#myDiv tr:nth-child(2) span:nth-child(2){
  color:red;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接