帮助伪类、第一个孩子

发布于 2024-08-30 10:06:36 字数 522 浏览 7 评论 0原文

我正在一个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

牵你的手,一向走下去 2024-09-06 10:06:36

它没有被忽略,只是没有任何匹配:)

我意识到这有点违反直觉,但是 :first-child 字面意思是父母的第一个孩子,不是父级的类型,因此代码中唯一与 :first-child 匹配的内容是

使用 .block:first-child 您是说具有 block 类的元素 是其父级的第一个子级,而不是说“第一个带有类 block”...它们是独立的选择器,在这里不重叠。那么,由于没有元素匹配这两个条件,因此没有匹配项,这更有意义吗?

它不支持所有浏览器,但您可以使用 :nth-child() 或 javascript 来做你想做的事情,例如在 jQuery 中它将是:

$("#main .block:first").css({ border: '1px solid red' });

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 of block and are the first child of their parent, it's not saying "the first one with class block"...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:

$("#main .block:first").css({ border: '1px solid red' });
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文