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;}
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.
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
?
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