【问题标题】:Z-index does not work between 2 react functional componentsZ-index 在 2 个反应功能组件之间不起作用
【发布时间】:2022-01-12 01:06:26
【问题描述】:

这是我的示例,我需要将第一个组件放在第二个之前。 目前,尽管 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;

【问题讨论】:

    标签: css reactjs components z-index


    【解决方案1】:

    你需要position: relative

    注意:z-index 仅适用于定位元素(位置:绝对、位置:相对、位置:固定或位置:粘性)和弹性项目(作为 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;
    

    【讨论】:

    • 刚刚添加了它,它不再工作了。顺便说一句,我知道这一点并忘记添加我的示例,但我之前尝试过它只是不想工作......
    【解决方案2】:

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

    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;
    

    【讨论】:

    • 没有任何改变。这里有什么意义?我的观点是在页面的两个部分之间制作视觉过渡效果。这就是为什么我需要重叠部分。
    • 您的代码可以正常运行。只需通过链接查看:codesandbox.io/s/recursing-clarke-gnpy7?file=/src/App.js
    • 你是对的隐藏,没关系。我现在明白了,我只是忘记设置背景颜色以查看它是否正常工作....谢谢!
    • 不客气
    【解决方案3】:

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

    【讨论】:

    • 这样尝试过,但它再次不起作用.....:
    • 可能是来自 react 的组件...这是个奇怪的问题..
    • 您需要在组件中添加 position: absolute 才能使 z-index 工作。这是一个代码沙箱:codesandbox.io/s/floral-frog-fie10?file=/src/Aaa.js。请注意,当您使用相对位置时,即使您应用负边距,元素也永远不会相互重叠。
    • 这就是阿比什亚伯拉罕!!!这是错误 - 负边距是问题所在!该示例运行良好,但我必须在我的相对组件之上有一些必须是绝对的,然后如果它超出我的基础,它将位于另一个组件之上!谢谢!!!!
    猜你喜欢
    • 2022-09-30
    • 1970-01-01
    • 1970-01-01
    • 2022-09-24
    • 2018-10-30
    • 2013-03-02
    • 2017-07-29
    • 2010-11-20
    • 2014-08-07
    相关资源
    最近更新 更多