.App {
font-family: sans-serif;
text-align: center;
}
.section-01 {
position: relative;
z-index: 0;
background-color: red;
color: white;
padding: 2rem;
}
.section-02 {
position: fixed;
z-index: 1;
background-color: blue;
color: white;
padding: 1rem;
top: 25vh;
left: 30vh;
}
.div-01 {
z-index: 2;
position: absolute;
background-color: purple;
padding: 1rem;
top: 15vh;
left: 25vh;
}
<section class="section-01">
Section-01
<div class="div-01">Div-01</div>
</section>
<section class="section-02">
<div>Section - 02</div>
</section>
I have a component like this:
<section id='section-01' style={{zIndex: 0}}>
<div id='div-01' style={{zIndex: 2}}>Hello World</div>
</section>
<section id='section-02' style={{zIndex: 1}}>
</section>
Now my problem is that due to absolute positioning of #section-02
and #div-01
, #section-02
takes the precedence and shows above #div-01
. However I don’t want that, I want #div-01
to show up above #section-02
and #section-02
show up above #section-01
.
Please note that I don’t have access to alter code of #section-01
or #section-02
. I can only control the code of #div-01
.
I know that if parent element has lower z-index
then its child won’t be able to show above any other entity in hierarchy of parent element and so no matter how high I set the value of div-01
it will always show below section-02
so I wanted to know how can I solve this problem?
Adding code sandbox for example: https://codesandbox.io/s/ecstatic-flower-u5plui?file=/src/styles.css
And here’s how I want it to be:
Please note that you’re only allowed to make changes in
.div-01 {
position: relative;
z-index: 2;
position: absolute;
background-color: purple;
padding: 1rem;
top: 6vh;
left: 25vh;
}
or in JSX part (HTML):
<div className="div-01">Div-01</div>
I don’t have access to section-01 or section-02.
I cannot restructure the HTML as these comes from different App owners and I have only control to div and its inner content.
2
Answers
You cant change the z-index of section-02 to -1 like this
If you want div-01 to appear on top of section-02 while maintaining section-01 below both, you will need to adjust the HTML structure slightly, by adding a common index context with position relative as shown below: