tags:

views:

33

answers:

3

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;}
+1  A: 

Not possible in your markup.

CSS selectors can only look at the ancestor axis. You cannot look sideways ("what else is there") and not inside ("what children do I have") - only upwards ("what are my parents").

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"> whose direct precedent sibling (in a way, that's looking "up", as well) is a <div class="header">.

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

Tomalak
A: 

You could possibly use some javascript to detect that. Check if menu is under header at load, and if it is, then set the margin-top of content to 100px

Ascherer
A: 

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?

nubbel
menu is out of the flow (absolutely positioned :)
Scott B
@nubbel - I'm trying to make some space above content for the menu, which is absolute positioned in that space. No need for the space if menu is not present.
Scott B