Billakosama
Billakosama

Reputation: 63

Stacking div elements

I want to stack some div elements like the picture below without having to manually enter the position of every new div I add. Is there some way I can write a style tha will stack my elements like this? I would like to avoid javascript.

Doing something like:

div{
  left:-30px;
}

will not work because its gonna move all of them by the same amount.

What I know I can probably do is have smaller divs as big as the gap next to each other and have them contain the bigger ones. The problem with this tho is I want to be able to change the stack order by manipulating the big element's z-index which wont work if they are children of different divs.

enter image description here Here is a stack snippet:

div {
  position: relative;
  float: left;
  width: 200px;
  height: 300px;
}
#div_1 {
  background-color: red;
}
#div_2 {
  background-color: blue;
}
#div_3 {
  background-color: yellow;
}
#div_4 {
  background-color: green;
}
<body>
  <div id="div_1">div1</div>
  <div id="div_2">div2</div>
  <div id="div_3">div3</div>
  <div id="div_4">div4</div>
</body>

Upvotes: 0

Views: 223

Answers (2)

Antoine Combes
Antoine Combes

Reputation: 1454

Is this what you are asking for ?

div {
  position: relative;
  float: left;
  width: 200px;
  height: 300px;
  margin-right: -50px;
  z-index: 0;
  box-shadow: 0 0 2px 2px rgba(0,0,0,0.8);
}
div:hover {
  z-index: 100
}
#div_1 {
  background-color: red;
}
#div_2 {
  background-color: blue;
}
#div_3 {
  background-color: yellow;
}
#div_4 {
  background-color: green;
}
<body>
  <div id="div_1">div1</div>
  <div id="div_2">div2</div>
  <div id="div_3">div3</div>
  <div id="div_4">div4</div>
</body>

Upvotes: 1

Suresh Karia
Suresh Karia

Reputation: 18218

Use dispaly:inline:block float:left;

enter image description here

body {
  background: #d300ff;
  margin: 0;
  padding: 0;
}
.strip {
  width: 100px;
  height: 700px;
  display: inline-block;
  margin: 0;
  padding: 0;
  float: left;
}
.strip1 {
  background: #fe0000;
}
.strip2 {
  background: #ffa901;
}
.strip3 {
  background: #41ff01;
}
.strip4 {
  background: #01b7ff;
}
.strip5 {
  background: #011eff;
}
<div class="strip strip1"></div>
<div class="strip strip2"></div>
<div class="strip strip3"></div>
<div class="strip strip4"></div>
<div class="strip strip5"></div>

Upvotes: 0

Related Questions