CSS:选择第一个相邻的兄弟 [英] CSS: Select the first adjacent sibling

查看:1018
本文介绍了CSS:选择第一个相邻的兄弟的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个HTML列表,如下所示:

I have an HTML list like so:

<ul>
  <li class="heading">Heading 1</li>
  <li class="heading">Heading 2</li>
  <li>Text Under Heading 2</li>
</ul>

由于Heading 1下没有文本,因此我想使用CSS隐藏它。

Since Heading 1 has no text under it, I want to hide it with CSS.

如果我这样做,

li.heading + li.heading { display: none; }

它隐藏标题2而不是标题1.

it hides Heading 2 instead of Heading 1.

如何隐藏标题1?有没有办法找到相邻的兄弟姐妹并选择第一个?

How can I hide Heading 1? Is there a way to look for adjacent siblings and select the first one?

推荐答案

实施。它将需要一个选择器,在它之后基于其兄弟选择一个元素。 CSS选择器可以基于前面的元素或外部元素来选择元素,但不能基于下面的元素或内部元素。

It is not possible using CSS as currently defined and implemented. It would require a selector that selects an element on the basis of its siblings after it. CSS selectors can select an element on the basis of preceeding or outer elements, but not on the basis of following or inner elements.

期望的效果可以使用JavaScript一个相当简单的方法,你可以根据目的决定是否从显示中删除元素或从文档树中完全删除它们。

The desired effect can be achueved using JavaScript in a rather straightforward way, and you can decide, depending on the purpose, whether you just remove the elements from display or completely remove them from the document tree.

这篇关于CSS:选择第一个相邻的兄弟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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