有没有办法在不使用3D变换/透视的情况下实现这一点?
* {
margin: 0;
box-sizing: border-box;
}
body,
html {
height: 100vh;
}
/* main = body (in real app) */
main {
transform-style: preserve-3d;
height: 100vh;
}
section.container {
display: contents;
position: relative;
height: 100vh;
}
section.container section.list {
transform-style: preserve-3d;
display: grid;
grid-template-rows: auto auto auto;
grid-row-gap: 10px;
position: absolute;
top: 50%;
left: 50%;
width: 45vw;
transform: translate(-50%, -50%);
}
div.item {
height: 50px;
background-color: white;
}
div.item.highlighted {
transform: translateZ(10px);
}
section.modal {
position: fixed;
top: 0;
left: 0;
width: 100vw;
height: 100vh;
background-color: #0009;
transform: translateZ(5px);
}
section.image {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
section.image img {
display: block;
object-fit: cover;
width: 100%;
height: 100%;
}
span.content {
background-color: white;
position: fixed;
top: calc(50% + 20vw);
left: 50%;
transform: translate(-50%, -50%);
}
<main>
<section class="container">
<section class="image">
<img src="https://html5up.net/uploads/demos/story/images/banner.jpg">
</section>
<section class="list">
<div class="item">Item 1</div>
<div class="item">Item 2</div>
<div class="item highlighted">Item 3</div>
</section>
</section>
<section class="modal">
<span class="content">modal content</span>
</section>
</main>
我相信堆叠上下文的创建规则不允许这样做。content
必须居中,最好的方法之一是使用position
、top/left
和transform: translate
。但是当你这样做时,一个新的堆叠上下文将被创建一个,所有.item
都被放在里面。这样,我只能将z-index
应用于.modal
的所有.item
,反之亦然。
3D 透视可以解决这个问题,但我想知道这是否是唯一的解决方案,或者是否有另一个解决方案(DOM 重组并.modal
放在其他地方,...我尝试了我能想到的一切,但没有成功,我仍然相信我错过了一些东西。
您可以避免所有变换并以不同的方式将元素居中,您可以使用z-index
.只需避免将任何z-index
设置为容器,即可避免创建堆叠上下文。仅将z-index
与模态元素和要突出显示的元素一起使用。
* {
margin: 0;
box-sizing: border-box;
}
body,
html {
height: 100vh;
}
/* main = body (in real app) */
main {
height: 100vh;
}
section.container {
height: 100vh;
display: flex;
}
section.container section.list {
display: grid;
grid-template-rows: auto auto auto;
grid-row-gap: 10px;
width: 45vw;
margin:auto;
position: relative;
}
div.item {
height: 50px;
background-color: white;
}
div.item.highlighted {
z-index:10;
position:relative;
}
section.modal {
position: fixed;
top: 0;
left: 0;
width: 100vw;
height: 100vh;
background-color: #0009;
z-index:5;
}
section.image {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
section.image img {
display: block;
object-fit: cover;
width: 100%;
height: 100%;
}
span.content {
background-color: white;
position: fixed;
top: calc(50% + 20vw);
left: 50%;
transform: translate(-50%, -50%);
}
<main>
<section class="container">
<section class="image">
<img src="https://html5up.net/uploads/demos/story/images/banner.jpg">
</section>
<section class="list">
<div class="item">Item 1</div>
<div class="item">Item 2</div>
<div class="item highlighted">Item 3</div>
</section>
</section>
<section class="modal">
<span class="content">modal content</span>
</section>
</main>