Css-translate & z-index

43 Views Asked by At

I've a problem here In the body of the html file there is this: <div>translate() issue</div> And I wanted to implement this shape by css: HTML + CSS So this is how I made it:

div {
        width: 300px;
        height: 200px;
        background-color: #eeeeee;

        display: flex;
        justify-content: center;
        align-items: center;
        color: #03a9f4;

        margin: 40px auto;
        position: relative;
}

div::before {
        content: "";
        background-color: #03a9f4;
        height: 100%;
        width: 100%;
        position: absolute;
        transform: rotate(-5deg);
        z-index: -1;
}

div::after {
        content: "";
        background-color: #e91e63;
        height: 100%;
        width: 100%;
        position: absolute;
        transform: rotate(5deg);
        z-index: -2;
}

And it worked actually, then I wanted to center the div using position and translate() like this:

div {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
}

Instead of autoing the margin left and right, but, the 'z-index' of div::before and div::after is not working anymore, because of transform property. Is there any solution or idea to use both of them correctly?

1

There are 1 best solutions below

0
Wongjn On

The transform property causes the <div> to be a new stacking context. This means the pseudo-elements within are contained inside the <div> element, meaning the <div> element cannot be in front of the pseudo-elements, so the <div> element's background color cannot be drawn on top of the pseudo-elements.

Instead, you could consider having another element inside the <div>, that can draw on top of the pseudo-elements:

div {
        width: 300px;
        height: 200px;
        background-color: #eeeeee;
        display: flex;
        justify-content: center;
        align-items: center;
        margin: 40px auto;
        position: relative;
}

p {
        background-color: #eeeeee;
        width: 100%;
        height: 100%;
        display: flex;
        justify-content: center;
        align-items: center;
        color: #03a9f4;
}


div::before {
        content: "";
        background-color: #03a9f4;
        height: 100%;
        width: 100%;
        position: absolute;
        transform: rotate(-5deg);
        z-index: -1;
}

div::after {
        content: "";
        background-color: #e91e63;
        height: 100%;
        width: 100%;
        position: absolute;
        transform: rotate(5deg);
        z-index: -2;
}

div {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
}
<div><p>translate() issue</p></div>