Ada*_*ers 213 css css-selectors css3
是否可以使用CSS3选择器:first-of-type
选择具有给定类名的第一个元素?我的测试没有成功,所以我认为不是吗?
守则(http://jsfiddle.net/YWY4L/):
p:first-of-type {color:blue}
p.myclass1:first-of-type {color:red}
.myclass2:first-of-type {color:green}
Run Code Online (Sandbox Code Playgroud)
<div>
<div>This text should appear as normal</div>
<p>This text should be blue.</p>
<p class="myclass1">This text should appear red.</p>
<p class="myclass2">This text should appear green.</p>
</div>
Run Code Online (Sandbox Code Playgroud)
Bol*_*ock 315
不,只使用一个选择器是不可能的.的:first-of-type
伪类选择其的第一个元素类型(div
,p
等).使用具有该伪类的类选择器(或类型选择器)意味着如果元素具有给定类(或具有给定类型)并且是其兄弟中的第一个类型,则选择该元素.
遗憾的是,CSS不提供:first-of-class
仅选择第一次出现的类的选择器.作为一种解决方法,您可以使用以下内容:
.myclass1 { color: red; }
.myclass1 ~ .myclass1 { color: /* default, or inherited from parent div */; }
Run Code Online (Sandbox Code Playgroud)
Bri*_*ell 43
CSS Selectors Level 4草案建议of <other-selector>
在:nth-child
选择器中添加语法.这将允许您挑选匹配给定其他选择器的第n个子项:
:nth-child(1 of p.myclass)
Run Code Online (Sandbox Code Playgroud)
以前的草稿使用了一个新的伪类,:nth-match()
因此您可能会在该功能的一些讨论中看到该语法:
:nth-match(1 of p.myclass)
Run Code Online (Sandbox Code Playgroud)
这已经在WebKit中实现,因此可以在Safari中使用,但它似乎是唯一支持它的浏览器.已经提交了实施Blink(Chrome),Gecko(Firefox)以及在Edge中实现它的请求的门票,但在这些方面没有明显进展.
小智 16
这是不是可以使用CSS3选择器:首个类型与给定的类名来选择的第一要素.
但是,如果目标元素具有前一个元素兄弟,则可以组合否定CSS伪类和相邻的兄弟选择器以匹配不立即具有相同类名的前一个元素的元素:
:not(.myclass1) + .myclass1
Run Code Online (Sandbox Code Playgroud)
完整的代码示例:
p:first-of-type {color:blue}
p:not(.myclass1) + .myclass1 { color: red }
p:not(.myclass2) + .myclass2 { color: green }
Run Code Online (Sandbox Code Playgroud)
<div>
<div>This text should appear as normal</div>
<p>This text should be blue.</p>
<p class="myclass1">This text should appear red.</p>
<p class="myclass2">This text should appear green.</p>
</div>
Run Code Online (Sandbox Code Playgroud)
我找到了一个供您参考的解决方案.从一些组div中选择两个相同类div的组第一个
p[class*="myclass"]:not(:last-of-type) {color:red}
p[class*="myclass"]:last-of-type {color:green}
Run Code Online (Sandbox Code Playgroud)
顺便说一句,我不知道为什么:last-of-type
有效,但:first-of-type
不起作用.
我在jsfiddle的实验... https://jsfiddle.net/aspanoz/m1sg4496/
这是一个旧线程,但我正在回应,因为它仍然在搜索结果列表中显得很高.现在未来已经到来,您可以使用:nth-child伪选择器.
p:nth-child(1) { color: blue; }
p.myclass1:nth-child(1) { color: red; }
p.myclass2:nth-child(1) { color: green; }
Run Code Online (Sandbox Code Playgroud)
:nth-child伪选择器功能强大 - 括号接受公式和数字.
更多信息:https://developer.mozilla.org/en-US/docs/Web/CSS/:NC-child
您可以通过选择属于同一类的兄弟类的每个元素并将其反转来完成此操作,这将选择页面上的几乎每个元素,因此您必须再次按类进行选择。
例如:
<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>
Run Code Online (Sandbox Code Playgroud)