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>
Since Heading 1 has no text under it, I want to hide it with CSS.
If I do this,
li.heading + li.heading { display: none; }
it hides Heading 2 instead of Heading 1.
How can I hide Heading 1? Is there a way to look for adjacent siblings and select the first one?
The CSS adjacent sibling selector is used to select the adjacent sibling of an element. It is used to select only those elements which immediately follow the first selector.
With the adjacent-sibling selector, you can apply styles to elements based on the elements which immediately precede them in the document.
No, there is no "previous sibling" selector. On a related note, ~ is for general successor sibling (meaning the element comes after this one, but not necessarily immediately after) and is a CSS3 selector. + is for next sibling and is CSS2. 1.
The general sibling selector (~) selects all elements that are next siblings of a specified element.
It is possible to target first sibling with CSS, with some limitations.
For the example in the question it could be done with something like this
li.heading { display: none; } /* apply to all elements */ li.heading + li.heading { display: list-item } /* override for all but first sibling */
This works, but requires that you can explicitly set the styles on the siblings to override the setting for first child.
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.
The desired effect can be achieved 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With