Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I select the first adjacent sibling?

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?

like image 626
Jeremy Avatar asked Jan 12 '12 00:01

Jeremy


People also ask

Which selector selects adjacent siblings?

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.

Which selector will apply a style to the adjacent sibling of the h1 tag?

With the adjacent-sibling selector, you can apply styles to elements based on the elements which immediately precede them in the document.

Is there a previous sibling selector?

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.

What is general sibling selector?

The general sibling selector (~) selects all elements that are next siblings of a specified element.


2 Answers

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.

like image 104
Eggert Jóhannesson Avatar answered Sep 21 '22 16:09

Eggert Jóhannesson


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.

like image 30
Jukka K. Korpela Avatar answered Sep 18 '22 16:09

Jukka K. Korpela