Amir Hasan Amir Hasan - 1 month ago 4
CSS Question

html5 card matching game - can't separate images from a sprite

I have a big sprite image which has around 16 images in it. I am want to cut images from the sprite and paste on the background image dynamically.

Edit: here is the Html code:
enter image description here

here is the css code :

body{
text-align:center;
background: BROWN url(../images/bg.jpg);
}
#game{
border-radius: 10px;
border: 1px solid GRAY;
background: DARKGREEN url(../images/table.jpg);
width: 500px;
height: 460px;
margin: 0 auto;
display: flex;
justify-content: center;
align-items: center;
}
.card{
perspective: 600px;
width: 80px;
height: 120px;
position: absolute;
transition: all .3s;
}

.face{
border-radius: 10px;
width: 100%;
height: 100%;
position: absolute;
transition-property: opacity, transition, box-shadow;
transition-duration: .3s;
backface-visibility: hidden;
}
.front{
background: GRAY url(../images/deck.png) 0 -480px;
}
.back{
background: LIGHTGREY url(../images/deck.png);
transform: rotate3d(0,1,0,-180deg);
}

.card:havor .face, .card-flipped .face {
box-shadow: 0 0 10px #aaa;
}
.card-flipped .front{
transform: rotate3d(0,1,0,180deg);
}
.card-flipped .back{
transform: rotate3d(0,1,0,0deg);
}
.card-removed{
opacity: 0;
}

.cardAJ {background-position: -800px 0;}
.cardAQ {background-position: -880px 0;}
.cardAK {background-position: -960px 0;}
.cardBJ {background-position: -800px -120px;}
.cardBQ {background-position: -880px -120px;}
.cardBK {background-position: -960px -120px;}
.cardCJ {background-position: -800px -240px;}
.cardCQ {background-position: -880px -240px;}
.cardCK {background-position: -960px -240px;}
.cardDJ {background-position: -800px -360px;}
.cardDQ {background-position: -880px -360px;}
.cardDK {background-position: -960px -360px;}


images

bg




bg

deck



*
deck

table




table

I am trying to split the image deck into pieces dynamically i.e. using jQuery code which is as follows:

$(function(){
//clone 12 copies of the card
for(var i=0; i<11;i++)
{
$(".card:first-child").clone().appendTo("#cards");
}
// initialise each card's position
$("#cards").children().each(function(index){
//align the cards to be 4*3 ourselves.
var x = ($(this).width()+20)*(index%4);
var y = ($(this).hegith+20)*Math.floor(index/4);
$(this).css("transform"," tranlateX( "+x+" px) tranlateY( "+y+" px)");

});


});

Please tell me what changes shall I make to get the desired result.

Answer

Your .card was stacked because you used position: absolute

Checkout this fiddle: Fiddle

Changing CSS:

.card {
  perspective: 600px;
  width: 80px;
  height: 120px;
  float: left;
  transition: all .3s;
  margin: 10px;
}

Notice: Close right your div <div class="face back"></div>

Comments