Conditional CSS: if a sibling child is present, then

In the html snippet below, I want the "main" div to have a background image only if there is no "menu" div in the markup. Is it 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>
+3
source share
3 answers

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

E + F Matches any element of F immediately preceding an element of EE: not (s) an element of E that does not correspond to a simple selector s

edit :not uses a simple selector, so unfortunately you cannot use it to filter on the properties of child elements, only the attributes of the element.

, , , , , .

.

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

, javascript, css .

JavaScript:

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

css:

body.no_menu .main{
    background:pink;
}
+9

css, , , html :

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

css ):

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

: http://jsfiddle.net/tYhxr/
( , div )

Keyo asnwer , .

html, javascript - .

, .

+2

You can add a second class to your main one <div>, which serves only to add the necessary background. Then, when you create the markup, you simply add a second class specifier in <div>if you need it, or omit it if you don't.

div.main {
  //main stuff
}

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

When your div menu is present, you use this:

<div class="main mainbg">

And when it is absent, you stick to:

<div class="main">
+1
source

Source: https://habr.com/ru/post/1778240/


All Articles