Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

css

In the markup below, I'm looking for a way (perhaps using css selector's) to style the content div differently depending on the presence of menu? Menu may or may not be present in that location in the markup and if it is there, I need to add some top margin to content.

I believe sibling and descendent selector rules might not go this far...

"When menu is present as a child of header set the top margin of content (whose parent is a sibling of header) 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;}
like image 779
Scott B Avatar asked Sep 30 '10 17:09

Scott B


2 Answers

Not possible in your markup.

CSS selectors can only look at the ancestor and at the sibling axes. You cannot look inside ("what children do I have") - only upwards ("what are my parents") and sideways ("what's next to me").

Examples. This:

div.header div.menu

refers to any <div class="menu"> one of whose ancestors is a <div class="header">.

This:

div.header > div.menu

refers to any <div class="menu"> whose direct ancestor (i.e. "parent") is a <div class="header">.

This:

div.header ~ div.menu

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

This:

div.header + div.menu

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

There are no other traversing selectors in CSS (this statement refers to CSS2) and certainly there are no conditionals.

like image 120
Tomalak Avatar answered Sep 29 '22 07:09

Tomalak


You could use jQuery:

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

Unfortunately the :has() selector didn't find its way into css3.

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

like image 27
nubbel Avatar answered Sep 29 '22 07:09

nubbel