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


当前回答

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

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

其他回答

我找到了一个解决方案供你参考。从一些组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>
    <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.col-md-4:nth-child(1).myclass{    
border: 1px solid #000;     
}        

这是不可能使用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 >