帮助伪类、第一个孩子
我正在一个 CMS 平台上工作,对模板文件的访问受到限制,并且想尝试使用伪类控制一些布局,但还没有成功。谁能看出这个结构有什么问题以及为什么我的伪类被忽略?
<div id="main">
<div class="someRandomDiv"></div>
<div class="block">
stuff
</div>
<div class="block">
more stuff
</div>
</div>
我正在尝试类似的东西
#main .block {border: 1px solid blue}
#main .block:first-child {border: 1px solid red}
,所以在这个例子中,我认为东西块将有一个红色边框,更多的东西将有一个蓝色,但它只是蓝色的。
感谢您对此的任何帮助。
I am working on a CMS platform with limited access to the template files and want to try and control some of the layout with pseudo class but no luck yet. Can anyone see what is wrong with this structure and why my pseudo class is being ignored?
<div id="main">
<div class="someRandomDiv"></div>
<div class="block">
stuff
</div>
<div class="block">
more stuff
</div>
</div>
and i am trying something like this
#main .block {border: 1px solid blue}
#main .block:first-child {border: 1px solid red}
so with this example I would think the stuff block would have a red border and more stuff would have a blue but it is all just blue.
Thanks for any help with this.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
它没有被忽略,只是没有任何匹配:)
我意识到这有点违反直觉,但是
:first-child
字面意思是父母的第一个孩子,不是父级的类型,因此代码中唯一与:first-child
匹配的内容是。
使用
.block:first-child
您是说具有block
类的元素 和 是其父级的第一个子级,而不是说“第一个带有类block
”...它们是独立的选择器,在这里不重叠。那么,由于没有元素匹配这两个条件,因此没有匹配项,这更有意义吗?它不支持所有浏览器,但您可以使用
:nth-child()
或 javascript 来做你想做的事情,例如在 jQuery 中它将是:It's not being ignored, there just aren't any matches :)
I realize it's a bit counter-intuitive, but
:first-child
literally means first child of the parent, not of the type, of the parent, so the only thing that matches:first-child
in your code is<div class="someRandomDiv"></div>
.With
.block:first-child
you're saying elements that have a class ofblock
and are the first child of their parent, it's not saying "the first one with classblock
"...they're independent selectors and don't overlap here. So, there are no matches since no element matches both conditions, that make more sense?It won't support all browsers, but you could use
:nth-child()
or javascript to do what you want, for example in jQuery it would be: