user2513528 user2513528 - 6 months ago 11
jQuery Question

Style a parent div based on another div

I am looking for a solution to apply CSS style to

div2
, only when
div1
is visible. How can I do that?

<div class="div1"></div>
<div class="div2"></div>

<style>
/* when div1 is NOT present */
.div2 {
margin: 100px auto 100px auto;
}

/* when div1 IS present */
.div2 {
margin: 0 auto 100px auto;
}
</style>

Answer

No Javascript required; you can use the CSS 'sibling' selector to achieve this:

.div2 {
    margin: 100px auto 100px auto;
}

.div1 + .div2 {
    margin: 0 auto 100px auto;
}

Of course this only applies when the .div1 element is not present in the DOM (as per the comment in your code sample). If you want to do this when div1 is present but hidden then you would need to use JS.