Home >Web Front-end >CSS Tutorial >Why Does `transform: rotate()` Cancel Out `z-index`?

Why Does `transform: rotate()` Cancel Out `z-index`?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-23 20:43:14440browse

Why Does `transform: rotate()` Cancel Out `z-index`?

Z-index Canceled by Transform(rotate)

Understanding the Behavior

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.

Issue Explanation

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.

Reason

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.

Solution

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.

Example

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn