I'd like to partially overlap multiple HTML elements - say DIVs - as in the below image. The black-bordered rectangles (Hanafuda cards) represent the elements I want to overlap.
With Javascript I'm sure I could come up with something, but I'd like to know if there's a pure CSS solution. I considered relative positioning but the problem is that each card needs a bigger and bigger offset along the x-axis.
Ideally I'd like the degree of overlap to depend on how much space there is, so that the elements crowd together more when cramped, but that's secondary and I don't mind using JS to accomplish it.
You can achieve that using flex, making all cards except the last one adjust to the remaining space
Here is a fiddle of the below:
.container {
display: flex;
width: 300px;
}
.card-container {
flex: 1 0 0;
overflow-x: hidden;
}
.card-container:last-child {
flex: 0 0 auto;
}
.card {
background: linear-gradient(to right, #ccc 0%, #444 100%);
width: 100px;
height: 150px;
}
<div class="container">
<div class="card-container">
<div class="card"></div>
</div>
<div class="card-container">
<div class="card"></div>
</div>
<div class="card-container">
<div class="card"></div>
</div>
<div class="card-container">
<div class="card"></div>
</div>
<div class="card-container">
<div class="card"></div>
</div>
</div>
This can also be achieved using display: table
, which currently enjoys greater browser compatibility over the newer, and wonderful, flex specification.
Compatibility: IE8+ and all modern browsers.
The outer div is given display: table
Each image is wrapped in a div with display: table-cell
table-layout: fixed
allows the "cells" to overlap
The outer div can be kept flexible to allow the images to overlap more / less depending on the space they left with
.cards {
display: table;
table-layout: fixed;
width: 50%;
max-width: 700px;
}
.cards > div {
display: table-cell;
width: 100px;
}
.cards > div > img {
display: block;
}
<div class="cards">
<div><img src="http://www.placehold.it/200x300" /></div>
<div><img src="http://www.placehold.it/200x300/FF0000" /></div>
<div><img src="http://www.placehold.it/200x300" /></div>
<div><img src="http://www.placehold.it/200x300/FF0000" /></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