I have a flexbox container that has two <div>s in it. One of the <div>s is the header, and the other <div> is hidden until an event is fired. When said event is fired, I want to make the hidden <div> appear on top of the other.
.container {
display: flex;
align-items: center;
justify-content: center;
}
.header {
max-width: 600px;
}
#content {
display: none;
max-width: 600px;
}
.changed #content {
display: block;
z-index: 100;
}
.changed .header {
opacity: .3;
z-index: 0;
}
<div class="container">
<div class="header">
<h1>Heading</h1>
<h2>Subheading</h2>
<div class="icons">Icons</div>
</div>
<div id="content"></div>
</div>
The class .changed is the class added to .container that renders the #content <div> visible. This part works fine.
The problem is that the .header and the #content <div>s are appearing side-by-side, even though they each have different z-index values. I think this is because of flexbox.
I've tried using different methods of horizontal and vertical centering, but flexbox has gotten me the closest to what I want. Is this the right approach and I'm just missing something? Should I go about this a different way?
Thanks!
Stack the flex items in a column:
.container { flex-direction: column; }
Make the container the containing block for absolute positioning:
.container { position: relative; }
Absolutely position the hidden div over the header:
#content {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
Then apply your JS and z-index as necessary.
.container {
display: flex;
align-items: center;
justify-content: center;
flex-direction: column;
position: relative;
}
.header {
max-width: 600px;
background-color: aqua;
}
#content {
/* display: none; */
max-width: 600px;
background-color: red;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
.changed #content {
/* display: block; <-- not necessary */
z-index: 100;
}
.changed .header {
opacity: .3;
z-index: 0;
}
<div class="container">
<div class="header">
<h1>Heading</h1>
<h2>Subheading</h2>
<div class="icons">Icons</div>
</div>
<div id="content">HIDDEN DIV
</div>
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With