繁体   English   中英

Z-index 在 2 个反应功能组件之间不起作用

[英]Z-index does not work between 2 react functional components

这是我的示例,我需要将第一个组件放在第二个之前。 目前,尽管 z-index,第二个组件位于第一个组件的前面。 我也尝试将样式放在组件标签上,但它不起作用。 我的错误在哪里?

第一个组件:

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;

第二部分

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;

应用程序:

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

export default App;

你需要position: relative

注意:z-index 仅适用于定位元素(位置:absolute,position:relative,position:fixed,或 position:sticky)和弹性项目(display:flex 元素的直接子元素)。

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

例如

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;

尝试为组件添加一个容器而不是片段,然后在该容器上应用 display: flex 和 flex-direction: 列,看看它是否有效。 编辑:代码沙箱修复: https://codesandbox.io/s/floral-frog-fie10?file=/src/Aaa.js

我不知道为什么它不起作用,这似乎没有原因。但是无论如何,也许你可以改用它:

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;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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