是否可以使用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 >


当前回答

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

其他回答

这是一个旧的帖子,但我回复,因为它仍然出现在搜索结果列表的高。现在,未来已经到来,您可以使用: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

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

<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>

我找到了一个解决方案供你参考。从一些组div选择从组的两个相同的类div的第一个

p[class*="myclass"]:not(:last-of-type) {color:red}
p[class*="myclass"]:last-of-type {color:green}

顺便说一句,我不知道为什么:最后一种类型的工作,但:第一种类型不工作。

我的jsfiddle实验…https://jsfiddle.net/aspanoz/m1sg4496/

我找到了有用的东西 如果你有一个更大的类,其中包含网格之类的东西,你的另一个类的所有元素 你可以这样做

div.col-md-4:nth-child(1).myclass{    
border: 1px solid #000;     
}        

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

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>