I'm working on a JavaScript game similar to "2048." It has a tabular display of "tiles" made up of several layers of divs. I'd like to make the selected tile "bounce" using a CSS animation. (The bouncing needs to be able to happen in each of the four cardinal directions: bounce up, down, left, or right, depending on the state of the game.)
My problem is that when I attach an animation, I see the content correctly bounce "in front of" tiles up and left of the selected one, but it incorrectly bounces "behind" the tiles to its right and below it. Here's a JSFiddle illustrating the problem:
https://jsfiddle.net/atqwc8er/2/
I'd like the bouncing blue tile "2" to show up in front of tile "3", the same way it already shows up in front of tile "1". Can anyone help me make it do that?
.tile {
position: absolute;
width: 50px;
height: 50px;
background-color: red;
}
.tile-inner {
text-align: center;
z-index: 10;
}
.tile-1-0 {
transform: translate(0px, 0px);
}
.tile-1-1 {
transform: translate(55px, 0px);
}
.tile-1-2 {
transform: translate(110px, 0px);
}
.selected .tile-inner {
background-color: blue;
animation: back-and-forth 0.5s infinite alternate;
z-index: 99; /* not working */
}
@keyframes back-and-forth {
from {
transform: translateX(-25px);
}
to {
transform: translateX(25px);
}
}
<div class="tile-container">
<div class="tile tile-1-0">
<div class="tile-inner">1</div>
</div>
<div class="tile tile-1-1 selected">
<div class="tile-inner">2</div>
</div>
<div class="tile tile-1-2">
<div class="tile-inner">3</div>
</div>
</div>
increase the z-index
of .selected
instead
.tile {
position: absolute;
width: 50px;
height: 50px;
background-color: red;
}
.tile-inner {
text-align: center;
z-index: 10;
}
.tile-1-0 {
transform: translate(0px, 0px);
}
.tile-1-1 {
transform: translate(55px, 0px);
}
.tile-1-2 {
transform: translate(110px, 0px);
}
.selected .tile-inner {
background-color: blue;
animation: back-and-forth 0.5s infinite alternate;
}
.selected {
z-index: 99;
}
@keyframes back-and-forth {
from {
transform: translateX(-25px);
}
to {
transform: translateX(25px);
}
}
<div class="tile-container">
<div class="tile tile-1-0">
<div class="tile-inner">1</div>
</div>
<div class="tile tile-1-1 selected">
<div class="tile-inner">2</div>
</div>
<div class="tile tile-1-2">
<div class="tile-inner">3</div>
</div>
</div>
Related question to get more details and understand why it cannot work with .title-inner
: Why can't an element with a z-index value cover its child?