CSS仅在有两个孩子的情况下才选择第一个孩子 [英] CSS select first child only if two children

查看:99
本文介绍了CSS仅在有两个孩子的情况下才选择第一个孩子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

只有在有第二个孩子的情况下,才可以选择第一个孩子吗?我只想隐藏第二个<p></p>标记.有什么办法用CSS做到这一点?

Is there any way to select the first child only if there is a second child? I'd like to hide the first <p></p> tag only if there is a second one. Is there any way to do this with CSS?

我的代码是这个

<div>
    <p></p>
    <p>something</p>
</div>

推荐答案

您只能通过组合:first-child:nth-last-child()来做到这一点,这意味着在纯CSS中,您将无法获得比IE9和更高版本更好的支持:

You can only do this by combining :first-child and :nth-last-child(), which means in pure CSS you won't get any better support than IE9 and later:

p:first-child:nth-last-child(2) {
    display: none;
}

如果您希望在第一个p完全有同级时隐藏(即,是否总共有2、3、4 ...个孩子都没关系),请改用此方法:

If you're looking to hide the first p when it has siblings at all (i.e. it doesn't matter whether there are 2, 3, 4... children in total), use this instead:

p:first-child:not(:only-child) {
    display: none;
}

这篇关于CSS仅在有两个孩子的情况下才选择第一个孩子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆