Home >Web Front-end >CSS Tutorial >Why Does `transform: rotate()` Cancel Out `z-index`?
In CSS, using the transform property can create a new "stacking context" on an element. This means that the element and its children form a separate layer in the rendering process. Additionally, elements with non-default z-index values also create their own stacking contexts.
In the provided code, the .test element has transform: rotate(10deg);, which creates a stacking context. Then, the .test:after pseudo-element is assigned z-index: -1. This, however, does not place it behind .test.
Z-index operates within a stacking context. By setting -webkit-transform on .test, it creates a new stacking context for the element and its children. As a result, z-index: -1 on .test:after only affects its position within the .test stacking context.
To solve this issue, ensure that both .test and .test:after share the same stacking context. One way to achieve this is by placing .test in a wrapping container and rotating the container instead.
Here's the updated code:
.wrapper { -webkit-transform: rotate(10deg); } .test { width: 150px; height: 40px; margin: 30px; line-height: 40px; position: relative; background: white; } .test:after { width: 100px; height: 35px; content: ""; position: absolute; top: 0; right: 2px; -webkit-box-shadow: 0 5px 5px #999; -webkit-transform: rotate(3deg); transform: rotate(3deg); z-index: -1; } <div class="wrapper"> <div class="test">z-index is canceled.</div> </div>
In this example, the transform rotation is applied to the .wrapper container, creating a single stacking context for both .test and .test:after. This allows z-index: -1 on .test:after to take effect as expected.
The above is the detailed content of Why Does `transform: rotate()` Cancel Out `z-index`?. For more information, please follow other related articles on the PHP Chinese website!