Reputation: 171
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>
Upvotes: 0
Views: 860
Reputation: 8319
The proper way of doing this kind of behaviour is setting a base class on their top level parent (could be even <body>
, and from there you can set any behaviour you want, purely by CSS.
.menu_open .div1 {
display: block;
}
.menu_open .div2 {
display: none;
}
.div1 {
display: none;
}
.div2 {
display: block;
}
<body class="menu_open">
<div class="div1">Div1</div>
<div class="div2">Div2</div>
</body>
Now you can toggle between the states of the <body>
classes using JS, and you can set complicated behaviours to any other elements, independent to other siblings.
Upvotes: 0
Reputation: 337733
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.
Upvotes: 3
Reputation: 1946
A little jQuery always helps,Use the :visible selector of jquery
if($('.div1').is(':visible'))
{
$('.div2').css('margin','0 auto 100px auto');
}
else
{
$('.div2').css('margin','100px auto 100px auto');
}
Upvotes: -1