CSS - 大于选择器 - 选择大于N的项目 [英] CSS - greater than selector - select items greater than N

查看:111
本文介绍了CSS - 大于选择器 - 选择大于N的项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的HTML正文中有几个< p> 元素。我只想显示前两个段落,并将 display:none 设置为所有段落。为什么以下代码无效?

I have several <p> elements in my HTML body. I only want to show the first two paragraphs, and set display:none to all paragraphs after. Why does the following code not work?

<html>

<head>
    <style type="text/css">
        p:gt(2) { display:none; }
    </style>
</head>
<body>
    <p>1</p>
    <p>2</p>
    <p>3</p>
    <p>4</p>
</body> 

</html> 

我的代码仍然显示Chrome浏览器中的所有4个段落元素。

My code still shows all 4 paragraph elements in Chrome web browser.

如何更正我的代码以实现我最初指出的目标?

How do I correct my code to achieve the objective I originally stated?

推荐答案

兄弟姐妹最简单的方法与一些向后兼容性将是:

If they're siblings the easiest approach with some backwards compatibility would be:

p + p ~ p {
    display: none;
}

JS Fiddle demo

您也可以使用:

p:nth-of-type(2) ~ p {
    display: none;
}

JS Fiddle demo

参考文献:

  • CSS Selectors.
  • CSS :nth-of-type() pseudo-class.
  • Adjacent sibling (+) combinators.
  • General sibling (~) combinators.

这篇关于CSS - 大于选择器 - 选择大于N的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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