Tricky CSS conditional brother> child selector> Can this be done?

In the markup below, I'm looking for a way (perhaps with a css selector) so that the style of the div div differs differently depending on the presence of the menu? The menu may or may not be at this markup location, and if there is one, I need to add the top edge to the content.

I believe that the rules of the selector and the child selector may not go that far ...

"When the menu is present as a child of the header, the top edge of the content (whose parent is the child of the header) is up to 100 pixels. Otherwise, set it to zero

<div class="header"> <div class="sitetitle">site title</div> <div class="tagline">tagline</div> <div class="menu">menu</div> </div> <div class="main"> <div class="content">content goes here</div> </div> 

If css allowed groupings, I would do it this way ...

 (.header ~ .menu) + (.main > .content) {margin-top:100px;} 
+6
css
source share
4 answers

Impossible in your markup.

CSS selectors can only look at the ancestor and on the axis of siblings. You cannot look inside ("that I have children") - only up ("that there are my parents") and sideways ("that is next to me").

Examples. It:

 div.header div.menu 

refers to any <div class="menu"> whose ancestors are <div class="header"> .

It:

 div.header > div.menu 

refers to any <div class="menu"> whose direct ancestor (ie, "parent") is <div class="header"> .

It:

 div.header ~ div.menu 

refers to any <div class="menu"> that has <div class="header"> among its previous siblings, i.e. they have the same parent element and occur one after another, but not necessarily adjacent to each other (which "looks sideways").

It:

 div.header + div.menu 

refers to any <div class="menu"> whose direct predecessor sibling is <div class="header"> .

There are no other move selectors in CSS (this statement applies to CSS2) and, of course, there are no conditional expressions.

+17
source share

You can use jQuery:

 ​$('.header:has(.menu) + .main > .content')​.css('margin-top', '100px');​​​​​​​​​​​ 

Unfortunately, the :has() selector did not find its way in css3.

But why don't you just apply margin-bottom to div.menu ?

+2
source share

You can use some javascript to detect this. Check if the menu is under the heading when loading, and if there is one, then set the top edge of the content to 100 pixels

0
source share

I used this CSS code in conditional formatting. Format index counting from the end.

 #stk-service-account-menu ul li:nth-last-child(1):before { 
0
source share

All Articles