我正在使用HTML5和CSS网格创建基于Sprite的游戏。 我为不同的元素(背景和前景)设置了不同的z-index
期望: 我以为多个元素可以占据相同的网格空间,但是显然,它们在移动时忽略了z-index。
结果:更改前景元素的网格区域会改变其余项目的顺序,而不是使其重叠
CSS:
#container {
position: relative;
height: 500px;
width: 500px;
display: grid;
grid-gap: 1px;
grid-template-columns: repeat(5, 20%);
grid-template-rows: repeat(5, 20%);
}
.item {
z-index: 0;
display: flex;
justify-content: center;
align-items: center;
background-size: 1600%;
image-rendering: pixelated;
}
@keyframes walk {
100% { background-position: -462px; }
}
#sprite {
z-index: 2;
background-color: transparent;
height: 100px;
width: 100px;
background: url(./../assets/thief.png) 0px 0px;
background-size: 1200%;
image-rendering: pixelated;
animation: walk 0.5s steps(5) infinite;
}
答案 0 :(得分:0)
下面是使用绝对位置的快速而又肮脏的初始方法–但是,只要深入研究,似乎可以通过使用带有grid-template-areas
的自定义列和行名称以及使用{{1}定位它们来实现覆盖网格单元格}。
grid-area
.container {
height: 500px;
width: 500px;
position: relative;
display: grid;
grid-gap: 5px;
grid-template-columns: repeat(5, 20%);
grid-template-rows: repeat(5, 20%);
grid-template-areas: "r1c1 r1c2 r1c3 r1c4 r1c5"
"r2c1 r2c2 r2c3 r2c4 r2c5"
"r3c1 r3c2 r3c3 r3c4 r3c5"
"r4c1 r4c2 r4c3 r4c4 r4c5"
"r5c1 r5c2 r5c3 r5c4 r5c5";
}
.item {
background: #eee;
padding: .25em;
z-index: 0;
}
#sprite {
grid-area: r2c3;
background: #ccc;
z-index: 5;
opacity: .5;
}
/* positioning the overlapped cell so the grid flow is intact */
/* you'll need to specify all the other cell classes also! */
.r2c3 {
grid-area: r2c3;
}
快速又脏的选项–对于任何覆盖的元素(如播放器精灵),您都可以对其进行绝对定位,以将其从网格布局中删除。例如:
<div class="container">
<div id="sprite">sprite</div>
<div class="item r1c1">1</div>
<div class="item r1c2">2</div>
<div class="item r1c3">3</div>
<div class="item r1c4">4</div>
<div class="item r1c5">5</div>
<div class="item r2c1">6</div>
<div class="item r2c2">7</div>
<div class="item r2c3">8</div>
<div class="item r2c4">9</div>
<div class="item r2c5">10</div>
<div class="item r3c1">11</div>
<div class="item r3c2">12</div>
<div class="item r3c3">13</div>
<div class="item r3c4">14</div>
<div class="item r3c5">15</div>
<div class="item r4c1">16</div>
<div class="item r4c2">17</div>
<div class="item r4c3">18</div>
<div class="item r4c4">19</div>
<div class="item r4c5">20</div>
<div class="item r5c1">21</div>
<div class="item r5c2">22</div>
<div class="item r5c3">23</div>
<div class="item r5c4">24</div>
<div class="item r5c5">25</div>
</div>