Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

css

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>
like image 841
Scott B Avatar asked Nov 29 '25 11:11

Scott B


2 Answers

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;
}
like image 57
Keyo Avatar answered Dec 02 '25 04:12

Keyo


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.

like image 33
Sebastian Patane Masuelli Avatar answered Dec 02 '25 05:12

Sebastian Patane Masuelli



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!