I'm trying to create a stack of playing cards in CSS, where each card is slightly offset diagonally from the one before it. Here's what it would look like:
.card {
float: left;
width: 100px;
height: 140px;
background-color: #fff;
border: 1px solid #000;
border-radius: 5px;
}
.card:nth-child(2) {
margin-left: -98px;
margin-top: -2px;
}
.card:nth-child(3) {
margin-left: -98px;
margin-top: -4px;
}
.card:nth-child(4) {
margin-left: -98px;
margin-top: -6px;
}
/* and so on... */
Example: http://jsfiddle.net/coev55w6/
I know I can do it by specifying different margins for each card, but I was wondering if there was a better way.
It's easy enough to create a purely horizontal offset:
.card {
float: left;
width: 100px;
height: 140px;
background-color: #fff;
border: 1px solid #000;
border-radius: 5px;
}
.card:not(:first-child) {
margin-left: -98px;
}
Purely vertical is easy too. But is there a way to get a diagonal offset with only a couple CSS rules?
It's a little bit of a hack, but you end up with that effect if you use the second option you gave:
.card:not(:first-child)
And put a <br>
after each card:
<div>
<div class=card></div><br>
<div class=card></div><br>
<div class=card></div><br>
<div class=card></div><br>
</div>
JSFiddle: http://jsfiddle.net/e4o0k2o5/
You could probably fine-tune it if you used a line-height
or something other than <br>
s.
I'm not sure it you're willing or able to change you HTML, but here's a wonderful alternative HTML layout and CSS to achieve your desired card spread.
.card {
width: 100px;
height: 140px;
background-color: #fff;
border: 1px solid #000;
border-radius: 5px;
position: relative;
margin-top: 10px;
margin-left: 10px;
}
.card2 {
width: 100px;
height: 140px;
background-color: #fff;
border: 1px solid #000;
border-radius: 5px;
position: relative;
margin-top: -10px;
margin-left: 10px;
}
<div>
<div class="card">
<div class="card">
<div class="card">
<div class="card"></div>
</div>
</div>
</div>
<br/>
<br/>
<br/>
<br/>
<div>
<div class="card2">
<div class="card2">
<div class="card2">
<div class="card2"></div>
</div>
</div>
</div>
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With