Partially overlap elements with CSS
I would like to partially overlap multiple HTML elements - say DIVs - as shown in the image below. The black rectangles ( Hanafuda ) represent the elements that I want to overlap.
With Javascript I'm sure I can think of something, but I would like to know if there is a pure CSS solution. I considered relative positioning, but the problem is that each map needs more and more displacement along the x-axis.
Ideally, I would like the degree of overlap to depend on how much space is there, so that the elements combine more when they are cramped, but this is secondary and I don't mind using JS to do it.
source to share
You can achieve this with flex by forcing all cards except the last one to adjust the remaining space
Below is the fiddle :
.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>
source to share
This can also be achieved with a tool display: table
that currently has more browser compatibility with the newer and better flex specifications.
Compatibility: IE8 + and all modern browsers.
-
Outer div set
display: table
-
Each image is wrapped in a div with
display: table-cell
-
table-layout: fixed
allows "cells" to overlap -
The outer div can be flexible to allow images to overlap more / less depending on the space they left with
Complete example
.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>
source to share