user3607282
user3607282

Reputation: 2555

Stack divs without giving a z-index

I want to overlap multiple tile divs over each other using margin-right: -10px.

I want the previous div to appear on top and new sibling divs after it. As it is, the previous div will be overlapped by the newer div. This can be easily solved by using float: right on the tile element and reversing the order.

But this solution is breaking another requirement I have. Which is, selecting the first same class after a another class.

.another + .same {
 outline: 1px solid red;
}

Is there a way to overlap the div as it is without using position absolute or a z-index. These tiles are dynamically added so adding a z-index means I would have to do it with javascript which I would like to avoid.

.tile {
  width: 30px;
  height: 30px;
  display: inline-block;
  margin-right: -10px;
  border: 2px solid white;
  border-radius: 100%;
}

.a {
  background-color: yellow;
}

.b {
  background-color: pink;
}

.c {
  background-color: turquoise;
}

.d {
  background-color: grey;
}

.containerA {
  margin-bottom: 30px;
  width: 150px;
  text-align: center;
}

.containerB {
  width: 150px;
}

.containerB .tile {
  float: right;
}

.another + .same {
  outline: 1px solid red;
}
<div class="containerA">
<div>
Normal
</div>
  <div class="tile a another">
  </div>
  <div class="tile b another">
  </div>
  <div class="tile c same">
  </div>
  <div class="tile d same">
  </div>
</div>

<div class="containerB">
<div>
Expected outcome with float right but sibling selector broken
</div>
  <div class="tile d same">
  </div>
  <div class="tile c same">
  </div>
  <div class="tile b another">
  </div>
  <div class="tile a another">
  </div>
</div>

Fiddle - https://jsfiddle.net/be51xxku/2/

Upvotes: 2

Views: 203

Answers (1)

Temani Afif
Temani Afif

Reputation: 273530

An idea is to change the CSS of your element to create this effect visually.

Here is an example where I used radial-gradient instead of background-color. I also used variable to make it easy to handle:

:root {
  --back-color: #fff;
}

.tile {
  width: 30px;
  height: 30px;
  display: inline-block;
  border-radius: 100%;
  margin-right: -15px;
  background: radial-gradient(circle at left, transparent 15px, var(--back-color) 16px);
}

.a {
  background: yellow
}

.b {
  --back-color: pink;
}

.c {
  --back-color: turquoise;
}

.d {
  --back-color: grey;
}

.containerA {
  margin-bottom: 30px;
  width: 150px;
  text-align: center;
}

.containerB {
  width: 150px;
}

.containerB .tile {
  float: right;
}

.another+.same {
  position: relative;
  outline: 1px solid red;
  z-index: -1;
}
<div class="containerA">
  <div>
    Normal
  </div>
  <div class="tile a another">
  </div>
  <div class="tile b another">
  </div>
  <div class="tile c same">
  </div>
  <div class="tile d same">
  </div>
</div>

Upvotes: 1

Related Questions