简体   繁体   中英

Z-index does not work between 2 react functional components

Here is my example where I need to put the first component in front of the second. Currently the second component is in front of the first despite z-index. I tried also to put style on the component tag but it does not work. Where is my mistake?

First component:

import styled from "styled-components";

const Container = styled.div`
position: relative;
display: flex;
justify-content: center;
align-items: center;
height: 500px;
z-index: 100;
`;

function Aaa() {

    return (
        <Container>asd</Container>
    )
}

export default Aaa;

Second component

import styled from "styled-components";

const Container = styled.div`
position: relative;
display: flex;
justify-content: center;
align-items: center;
height: 500px;
margin-top: -200px;
background: pink;
z-index: 1;
`;

function Bbb() {

    return (
        <Container>qwe</Container>
    )
}

export default Bbb;

App:

function App() {
  return (
    <>
    <Aaa />
    <Bbb />
    </>
  );
}

export default App;

You need position: relative .

Note: z-index only works on positioned elements (position: absolute, position: relative, position: fixed, or position: sticky) and flex items (elements that are direct children of display:flex elements).

https://www.w3schools.com/cssref/pr_pos_z-index.asp

Eg

import styled from "styled-components";

const Container = styled.div`
position: relative;
display: flex;
justify-content: center;
align-items: center;
height: 500px;
margin-top: -200px;
background: pink;
z-index: 1;
`;

function Bbb() {

    return (
        <Container>qwe</Container>
    )
}

export default Bbb;

Try adding a container for the components instead of fragment and apply display: flex and flex-direction: column on that container and see if it works. Edit: Code sandbox with fix: https://codesandbox.io/s/floral-frog-fie10?file=/src/Aaa.js

I dont know why it not work,this seems no reason.But what ever, maybe you could use this instead:

import styled from "styled-components";
const Container = styled.div`
    position: relative;
    display: flex;
    justify-content: center;
    align-items: center;
    height: 500px;
    transform: translateY(0px);
    `;

    function Aaa() {

    return (
        <Container>asd</Container>
    )
    }

    export default Aaa;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM