是否可以使用CSS3选择器:first-of-type选择具有给定类名的第一个元素?我的测试不成功,所以我想这不是?

守则(http://jsfiddle.net/YWY4L/):)

p: first-of-type{颜色:蓝色} p.myclass1: first-of-type{颜色:红} .myclass2: first-of-type{颜色:绿色} < div > <div>此文本应该正常显示</div> <p>这个文本应该是蓝色的 <p class="myclass1">这段文字应该是红色的 <p class="myclass2">这段文字应该是绿色的 < / div >


当前回答

这是不可能使用CSS3选择器:first-of-type选择具有给定类名的第一个元素。

但是,如果目标元素有一个先前的兄弟元素,你可以结合否定CSS伪类和相邻的兄弟元素选择器来匹配一个没有立即具有相同类名的前一个元素的元素:

:not(.myclass1) + .myclass1

完整的工作代码示例:

p: first-of-type{颜色:蓝色} P:not(.myclass1) + .myclass1{颜色:红色} P:not(.myclass2) + .myclass2{颜色:绿色} < div > <div>此文本应该正常显示</div> <p>这个文本应该是蓝色的 <p class="myclass1">这段文字应该是红色的 <p class="myclass2">这段文字应该是绿色的 < / div >

其他回答

作为一个后备方案,你可以像这样在父元素中包装你的类:

<div>
    <div>This text should appear as normal</div>
    <p>This text should be blue.</p>
    <div>
        <!-- first-child / first-of-type starts from here -->
        <p class="myclass1">This text should appear red.</p>
        <p class="myclass2">This text should appear green.</p>
    </div>
</div>

不知道怎么解释,但我今天遇到了类似的事情。 无法设置.user:first-of-type{}而.user:last-of-type{}正常工作。 这是固定后,我包装他们在一个div没有任何类或样式:

https://codepen.io/adrianTNT/pen/WgEpbE

<style>
.user{
  display:block;
  background-color:#FFCC00;
}

.user:first-of-type{
  background-color:#FF0000;
}
</style>

<p>Not working while this P additional tag exists</p>

<p class="user">A</p>
<p class="user">B</p>
<p class="user">C</p>

<p>Working while inside a div:</p>

<div>
<p class="user">A</p>
<p class="user">B</p>
<p class="user">C</p>
</div>

简单地说:第一个对我有用,为什么还没有提到这个?

这是一个旧的帖子,但我回复,因为它仍然出现在搜索结果列表的高。现在,未来已经到来,您可以使用:n -child伪选择器。

p:nth-child(1) { color: blue; }
p.myclass1:nth-child(1) { color: red; }
p.myclass2:nth-child(1) { color: green; }

:n -child伪选择器功能强大——括号接受公式和数字。

更多信息请点击:https://developer.mozilla.org/en-US/docs/Web/CSS/:nth-child

您可以通过选择类中相同类的兄弟元素并反转它来实现这一点,这将选择页面上的几乎所有元素,因此您必须再次按类进行选择。

eg:

<style>
    :not(.bar ~ .bar).bar {
        color: red;
    }
<div>
    <div class="foo"></div>
    <div class="bar"></div> <!-- Only this will be selected -->
    <div class="foo"></div>
    <div class="bar"></div>
    <div class="foo"></div>
    <div class="bar"></div>
</div>