Scott B
Scott B

Reputation: 40157

Conditional CSS: if sibling's child div is present, then

In the html fragment below, I want the "main" div to have a background image only if "menu" div is not present in the markup. Is this possible?

<div class="header">
    <div class="siteTitle">site title</div>
    <div class="tagline">site tagline</div>
    <div class='menu'></div>
</div>
<div class="main"></div>

Upvotes: 3

Views: 22631

Answers (3)

Benbob
Benbob

Reputation: 14244

http://www.w3.org/TR/css3-selectors/

E + F Matches any F element immediately preceded by a sibling element E. E:not(s) an E element that does not match simple selector s

edit :not uses a simple selector, so unfortunately you can't use it to filter by properties of children, only attributes of the element.

A simple selector is either a type selector, universal selector, attribute selector, class selector, ID selector, or pseudo-class.

You could however put a .empty class on the menu and still use it.

.header .menu:not(.empty) + .main {
   background:pink;
}

This solution is the best of both worlds, javascript but using css as per normal.

javascript:

if ($('.menu').length == 0){
    $('body').addClass('no_menu');
}

css :

body.no_menu .main{
    background:pink;
}

Upvotes: 9

The only pure css solution i see is only possible if you rearrange your html like so:

<div class="header">
    <div class="siteTitle">site title</div>
    <div class="tagline">site tagline</div>
</div>
<div class="menu"></div>
<div class="main"></div>

then you can use this css to only apply a property):

.menu { background: none }
.menu ~ .main{ background: url() } /* or .menu + .main if they are guaranteed to be adjacent to each other on the code */

in this example, you can see it at work: http://jsfiddle.net/tYhxr/
(test it by deleting the menu div and running it again)

check Keyo's asnwer for a link about how selectors work.

If you can't change the html, the javascript is the way to go.

I hope this helps.

Upvotes: 3

anon
anon

Reputation:

You could add a second class to your main <div> that only serves to add the background you want. Then when you create the markup, you just add the second class specifier to the <div> if you need it, or omit it if you don't.

div.main {
  //main stuff
}

div.mainbg {
  background: *background-specifications*;
}

When your menu div is present, you use this:

<div class="main mainbg">

And when it's missing, you stick with:

<div class="main">

Upvotes: 1

Related Questions