html - ::在悬停更改之前的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>
)
谢谢你!
解决方案
转换元素会改变堆叠上下文。
您可以使用负边距移动元素,而不是平移。
更新:并通过在悬停时在右侧和底部添加边距同时在顶部和左侧将其移走来补偿这一点(以便以下内容不会移动)。
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>
推荐阅读
- python - python中是否有一种方法可以随机选择具有权重且无替换的元组子集?
- c# - 在 NTFS 上重命名目标文件后,如何防止修改快捷方式路径?
- delphi - How to free HRGN after CreatePolygonRgn?
- firebase - 新的 Firestore 规则发布
- javascript - 通过 AJAX 传递 POST 请求,Django 问题
- sass - 如何通过单击复选框(不带 JavaScript)在 SCSS 中缩放另一个 div?
- c# - 在 C# 中使用原始类型?
- algorithm - 为什么在 0-1 背包问题中我们使用 INT_MIN 以及为什么 0 不起作用
- continuous-integration - 大堂:vars vs params
- microsoft-teams - Microsoft Teams 自定义选项卡 | MS 团队 android 应用程序的后退按钮未按预期工作