英文:
z-index and translate 3d not work the same in chrome and safari
问题
我遇到了一个浏览器兼容性问题,发现是由Google Chrome和Safari处理z-index和translate 3D方式不同引起的。我在这里创建了一个最小示例:
<div>
<div style="background-color: blue; height: 100px; width: 100px; position: absolute; transform: translate3d(10px, 10px, 10px)"></div>
<div style="background-color: red; height: 100px; width: 100px; position: relative; z-index: 1"></div>
</div>
这个简短的HTML在Safari和Google Chrome中显示方式不同。
我想知道哪一个是预期的行为?我应该如何正确地同时使用z-index和transform?我在不同的浏览器中尝试过并创建了一个最小示例。
英文:
I experience a browser compatible issue and and found it is caused by Google chrome and Safari process z-index and translate 3D differently. I make a minimum example here:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-html -->
<div>
<div style="background-color: blue; height: 100px; width: 100px; position: absolute; transform: translate3d(10px, 10px, 10px)"></div>
<div style="background-color: red; height: 100px; width: 100px; position: relative; z-index: 1"></div>
</div>
<!-- end snippet -->
This short html, display differently in Safari and Google Chrome.
May I know which one is the expect behaviour? How should I correctly use z-index and transform at the same time?
I tried in different browsers and make a minimum example.
答案1
得分: 1
Safari也可以使用translate3d属性作为浏览器中的一层,并且它有不同的显示方法,因此如果您在元素上使用z-index并在其他元素上使用translateZ,translateZ或translate3d将覆盖z-index元素。
因此,为了避免在Safari中出现问题,我建议您像下面的注释中所示使用translateY和translateX方法,或者将translateZ设置为与您设置z-index相同。
这里有关Safari的更多信息:https://bugs.webkit.org/show_bug.cgi?id=61824
示例:
英文:
Safari work with translate3d property as a layer in the browser too and it has this different display method, so if you put elements with z-index and others with translateZ, translateZ or translate3d will work over z-index elements
So, to avoid issues with safari I would suggest you to use translateY and translateX methods as is shown in comment below, or set translateZ as same you are setting z-index
Here is more about that in Safari: https://bugs.webkit.org/show_bug.cgi?id=61824
Example:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-css -->
.box {
height: 100px;
width: 100px;
}
.blue {
background-color: blue;
position: absolute;
/** this works in safari **/
transform: translateY(10px) translateX(10px);
transform: translate3d(10px, 10px, 10px);
}
.red {
background-color: red;
position: absolute;
/** this desn't work in safari */
/** transform: translate3d(0, 0, 9px); */
/** need this to work with safari */
/** transform: translate3d(0, 0, 11px); */
z-index: 1;
}
<!-- language: lang-html -->
<div>
<div class="box blue"></div>
<div class="box red"></div>
</div>
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论