html - 转换伪元素和父元素时 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>
解决方案
一个简单的解决方法是考虑另一个伪元素来创建灰色背景,并且您最初使它们都属于相同的堆叠上下文(通过添加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>
推荐阅读
- symfony - 您如何通过 Sonata 获得实体的管理服务?
- asp.net - Simple Web 应用程序的正确安全方法
- ios - 图像坐标空间和屏幕坐标空间iOS之间的转换
- sta - 如何从 C++ winRT 中的 FileOpenPicker 窗口获取所选文件?
- webpack - 如何使用 Webpack / Laravel 调试生产 Vue.js 2 编译代码
- java - 错误:在减去 Integer 和 int 时,二元运算符“-”的操作数类型错误
- android - AlertDialog setContentView 不工作 API22
- javascript - 通过 npm (nodejs) 管理不同的代码库 (github repos)
- android - 阻止根用户安装我的应用程序
- sap - BO - 派生表中的对象