Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Diagonal stack effect in CSS

Tags:

css

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?

like image 591
jobo3208 Avatar asked Dec 16 '14 20:12

jobo3208


2 Answers

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.

like image 191
mopo922 Avatar answered Nov 19 '22 14:11

mopo922


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>
like image 24
Drazzah Avatar answered Nov 19 '22 15:11

Drazzah