Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Partially overlap elements using CSS

Tags:

html

css

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.

enter image description here

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.

like image 879
Jack M Avatar asked Jun 30 '15 01:06

Jack M


2 Answers

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>
like image 130
y34h Avatar answered Oct 12 '22 22:10

y34h


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

Full 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>
like image 34
misterManSam Avatar answered Oct 12 '22 22:10

misterManSam