'Subcomponent with higher z-index value than its parents z-index?
I am working on a project where there are three components displayed from top to bottom as rows. The footer should go underneath the top 2 components ('component1', 'component2') while scrolling. The footer has a function called ToggleBlue which is a button that when clicked shows the blue component. The footer should be displayed underneath all other components and the blue component should be displayed above all other components (when toggled).
src/App.js
import React from ‘react’;
function App() {
return ( <>
<Component1 />
<Component2 />
<Footer />
</> );
}
export default App
src/components/Footer/index.js
import React from ‘react’;
import { ToggleBlue } from ‘./toggleBlue’;
function Footer() {
return (
<ul>
<Component />
<Component />
<ToggleBlue />
</ul>
)
}
export default Footer
src/components/Footer/toggleBlue.js
import React, { useState } from ‘react’;
import Blue from ‘./../../components/Blue/index.js’
export function ToggleBlue() {
const [show, setShow] = useState(true)
return ( <>
{
show?<Blue style={{zIndex:5}} /> : null
}
<button onClick={() => setShow(!show)}>Show Blue</button>
</> )
}
What I tried
- Setting component1 and component2's z-index to 2, the footer's z-index to 0, and blue's z-index to 5 (using CSS and JS).
- Restructuring my project so that blue is in my App.js file, however, it causes a lot of issues as the footer is responsive and the position of the blue component is relative to the elements in the footer.
What I expected
I expected the footer to display underneath component 1 and 2 and for the blue component (when toggled) to display above all components.
What resulted
The blue component displays above the footer but below component1 and component2. I believe this is because a component being called from within another component might take its parent components z-index value. Codesandbox code
Solution 1:[1]
Is this what you wanted?
Just remove z-index
from your footer and add position: relative
to your component, because without that z-index
won't work.
UPD: probably you don't need to make your footer scroll behind your components. Usually the footer just stays at the bottom of the page and if there is not enough height it stays at the bottom of the content. You could check it here https://css-tricks.com/couple-takes-sticky-footer/
https://codesandbox.io/s/beautiful-ellis-5zbjhr?resolutionWidth=320&resolutionHeight=452
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Georgy |