我已经在这个问题上摸不着头脑了一段时间,无法弄清楚为什么它不起作用。我基本上只是尝试使用CSS隐藏页面上的某些特定内容 - 对于这项工作,我无法访问页面HTML,但可以随意注入CSS。
好的,我有一个基本的HTML结构如下:
<div id="content-body">
<p> want this to stay </p>
<h2>want this to stay</h2>
<p> want this to stay </p>
<p> want this to stay </p>
<p> want this removed </p>
<h2>want this removed</h2>
<p> want this removed </p>
<p> want this removed </p>
</div>
我整合了以下CSS来删除整个&#34; content-body&#34;元素然后在特定的子元素上覆盖它,但它似乎不起作用。
#content-body {display:none}
p:nth-child(1) {display:block !important}
h2:nth-child(2) {display:block}
p:nth-child(3) {display:block}
p:nth-child(4) {display:block}
重要的标签似乎没有任何区别。关于我如何格式化这个有什么不正确的吗? (实际页面的HTML比示例多得多,因此通过CSS删除所有内容比单独选择元素要容易得多,尽管我可能需要这样做)
答案 0 :(得分:2)
您通过调用隐藏父元素:
#content-body {display:none}
所以无论你如何瞄准他们,所有的孩子都会被隐藏起来。您需要做的是隐藏p
中的h2
和#content-body
元素,然后使用nth-of-type
代替nth-child
覆盖您要显示的元素(因为你想要定位第一个h2
和第三个p
等),如下所示:
#content-body p, #content-body h2 {
display: none;
}
#content-body p:nth-of-type(1),
#content-body p:nth-of-type(2),
#content-body p:nth-of-type(3),
#content-body h2:nth-of-type(1) {
display: block;
}
答案 1 :(得分:1)
您可以选择具有全局选择器的所有直接子项,然后您可以覆盖:
#content-body > * { display: none }
#content-body p:nth-child(1),
#content-body h2:nth-child(2),
#content-body p:nth-child(3),
#content-body p:nth-child(4) { display: block }
此处示例:jsfiddle
答案 2 :(得分:0)
您的第一个选择器#content-body { display: none; }
隐藏了所有内容,因为它是容器。首先通过定位p
和h2
来隐藏所有元素,然后选择性地显示带有nth-of-type selector的元素。
#content-body p,
#content-body h2 { display: none }
#content-body p:nth-of-type(1) { display: block }
#content-body h2:nth-of-type(1) { display:block }
#content-body p:nth-of-type(2) { display:block }
#content-body p:nth-of-type(3) { display:block }
<div id="content-body">
<p>want this to stay</p>
<h2>want this to stay</h2>
<p>want this to stay</p>
<p>want this to stay</p>
<p>want this removed</p>
<h2>want this removed</h2>
<p>want this removed</p>
<p>want this removed</p>
</div>