如何用Transform覆盖CSS Z-Index堆叠上下文?红色方块层级问题求助
尝试让红色方块显示在表格上方,已查阅Z-index堆叠上下文相关文章及Stack Overflow的《Override CSS Z-Index Stacking Context》内容,推测可通过Transform解决,但当前方案无效,恳请提供解决方案建议。

HTML代码
<!DOCTYPE html> <html lang="en"> <head> <title>Home</title> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width" /> <link rel="stylesheet" href="styles.css" /> <script type="module" src="script.js"></script> </head> <body> <div class="top"> <table> <thead> <tr> <th colspan="2">The table header</th> </tr> </thead> <tbody> <tr> <td>The table body</td> <td>with two columns</td> </tr> </tbody> </table> </div> <div class="bottom"> <div> <div><span class="red">Red</span></div> <div><span class="green">Green</span></div> <div><span class="blue">Blue</span></div> </div> </div> </body> </html>
CSS代码
.top { z-index: 2; position: relative; } .bottom { z-index: 1; position: relative; } table, td { border: 1px solid #333; z-index: 4; position: relative; background-color: #fff; } thead, tfoot { background-color: #333; color: #fff; } .red, .green, .blue { position: absolute; width: 100px; color: white; line-height: 100px; text-align: center; } .red { z-index: 111; top: -40px; left: 20px; background: red; transform: translateZ(1px); } .green { top: -20px; left: 60px; background: green; } .blue { top: -10px; left: 100px; background: blue; } body, div:first-child { transform-style: preserve-3d; }
解决方案
问题核心是堆叠上下文的层级限制:.top和.bottom都设置了position: relative和z-index,这会让它们各自创建独立的堆叠上下文。.top的z-index:2高于.bottom的z-index:1,所以.bottom内部的所有元素,无论自身z-index多高,都会被.top的堆叠上下文覆盖——这也是你用transform: translateZ(1px)无效的原因,这个操作只能在.bottom自己的堆叠上下文里提升层级,无法突破到外部。
方法1:移除.top的z-index,消除独立堆叠上下文
修改.top的CSS,去掉z-index属性,这样它不再创建独立的堆叠上下文,表格的z-index会和红色方块处于同一个上下文(body的堆叠上下文),此时红色方块的高z-index就能生效:
.top { position: relative; /* 移除 z-index: 2; */ }
方法2:调整.bottom的堆叠上下文层级
如果需要保留.top的堆叠上下文,可以把.bottom的z-index设为比.top更高(比如3),这样.bottom的整个堆叠上下文会在.top上方,红色方块自然也能显示在表格上面:
.bottom { z-index: 3; position: relative; }
注意:此方法会让.bottom里的绿色、蓝色方块也显示在表格上方,如果你只需要红色方块显示在上方,方法1更合适。
方法3:将红色方块移出.bottom的堆叠上下文
修改HTML结构,把红色方块的元素从.bottom中移出,直接放到body下,这样它不再受.bottom堆叠上下文的限制,再配合高z-index就能覆盖表格:
<body> <div class="top"> <!-- 表格内容不变 --> </div> <span class="red">Red</span> <!-- 移到这里 --> <div class="bottom"> <!-- 绿色、蓝色方块内容不变 --> </div> </body>
同时可以保留红色方块的原有CSS样式,无需额外修改。
内容的提问来源于stack exchange,提问作者user42195

