首页 > 解决方案 > ::在悬停更改之前的Z-index?

问题描述

我正在创建一个简单的 CSS 按钮,但它的 z-index 存在问题。

我的代码:

body { /* Ignore Body Styling */
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
}

button {
  padding: 0.7em 1em;
  font-size: 25px;
  text-transform: uppercase;
  font-weight: 600;
  border: 5px solid #191919;
  border-radius: 0;
  background-color: rebeccapurple;
  color: #fff;
  position: relative;
}

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

button::before {
  content: "";
  position: absolute;
  top: 10px;
  left: 10px;
  width: 100%;
  height: 100%;
  z-index: -1;
  background-color: rgb(147, 103, 190);
}

button:hover::before {
  transform: translate(15px, 15px);
  z-index: -1;
}
<button>Click Me</button>

只需运行一次代码,您就会明白。

虽然:hover,我不想::before覆盖我主要元素(<button>

谢谢你!

标签: htmlcss

解决方案


转换元素会改变堆叠上下文。

您可以使用负边距移动元素,而不是平移。

更新:并通过在悬停时在右侧和底部添加边距同时在顶部和左侧将其移走来补偿这一点(以便以下内容不会移动)。

body {
  /* Ignore Body Styling */
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
}

button {
  padding: 0.7em 1em;
  font-size: 25px;
  text-transform: uppercase;
  font-weight: 600;
  border: 5px solid #191919;
  border-radius: 0;
  background-color: rebeccapurple;
  color: #fff;
  position: relative;
}

button:hover {
  cursor: pointer;
  margin-top: -10px;
  margin-left: -10px;
  margin-bottom: 10px;
  margin-right: 10px;
}

button::before {
  content: "";
  position: absolute;
  top: 10px;
  left: 10px;
  width: 100%;
  height: 100%;
  z-index: -1;
  background-color: rgb(147, 103, 190);
}

button:hover::before {
  transform: translate(15px, 15px);
  z-index: -1;
}
<button>Click Me</button>


推荐阅读