首页 > 解决方案 > 转换伪元素和父元素时 z-index 不起作用

问题描述

当前我正在尝试在 X 和 Y 轴上平移一个父元素 10px,同时::after在其他方向上变换一个相等的量(这是为了模拟伪元素无处移动的体验)。我预计这将是相当微不足道的,但是,在::after转换时不想留在它的父级后面。我认为创建一个新的堆叠上下文会起作用,而且我以前从未遇到过这个问题(拥有多年的 CSS 经验)。

body {
  background-color: #FFF;
}

button {
  padding: .75rem 1rem;
  background-color: #eee;
  border: none;
  font-weight: 500;
  font-size: 1rem;
  position: relative;
  transition: ease all .15s;
}

button::after {
  content: '';
  position: absolute;
  z-index: -1;
  height: 100%;
  width: 100%;
  background-color: #000;
  top: 0;
  left: 0;
  transition: ease all .15s;
}

button:hover {
  transform: translate(-10px, -10px);
}

button:hover::after {
  transform: translate(10px, 10px);
} 
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>Fun Button</title>
</head>
<body>
  
  <button type="button">Fun Button!</button>

</body>
</html>

标签: htmlcsscss-transforms

解决方案


一个简单的解决方法是考虑另一个伪元素来创建灰色背景,并且您最初使它们都属于相同的堆叠上下文(通过添加z-index到按钮),因此在添加转换时不会有任何问题

body {
  background-color: #FFF;
}

button {
  padding: .75rem 1rem;
  border: none;
  font-weight: 500;
  font-size: 1rem;
  position: relative;
  z-index:0;
  transition: ease all .15s;
}

button::after,
button::before{
  content: '';
  position: absolute;
  z-index: -2;
  height: 100%;
  width: 100%;
  background-color: #000;
  top: 0;
  left: 0;
  transition: ease all .15s;
}
button::before{
  z-index:-1;
  background-color: #eee;
}

button:hover {
  transform: translate(-10px, -10px);
}

button:hover::after {
  transform: translate(10px, 10px);
}
<button type="button">Fun Button!</button>


推荐阅读