-2

I want the red box to be rendered in front of the following flex items, but nothing I tried leads to this sort of order.

.box {
  font-size: 2.5rem;
  width: 100px;
  line-height: 100px;
  text-align: center;
}

.front .box {
  margin: 20px auto;
}

.back {
  display: flex;
  justify-content: center;
  max-width: 600px;
  margin: 0 auto;
  border: 1px solid #ccc;
  padding: 20px 0;
}

.green {
  background: green;
}

.yellow {
  background: yellow;
}

.red {
  background: red;
}
<div class="back">
  <div class="box yellow">
    <div class="box red" style="position:block; margin-left: 50px; z-index: 99999">2</div></div>
  <div class="box green">2</div>
</div>
Temani Afif
  • 245,468
  • 26
  • 309
  • 415
28Smiles
  • 104
  • 1
  • 6

2 Answers2

2

Change it from position: block to position: absolute. There is no position: block, and you must use a proper positioning attribute to get z-index to work properly.

.box {
  font-size: 2.5rem;
  width: 100px;
  line-height: 100px;
  text-align: center;
}

.front .box {
  margin: 20px auto;
}

.back {
  display: flex;
  justify-content: center;
  max-width: 600px;
  margin: 0 auto;
  border: 1px solid #ccc;
  padding: 20px 0;
}

.green {
  background: green;
}

.yellow {
  background: yellow;
}

.red {
  background: red;
}
<div class="back">
  <div class="box yellow">
    <div class="box red" style="position:absolute; margin-left: 50px; z-index: 99999">2</div></div>
  <div class="box green">2</div>
</div>
Nick
  • 1,392
  • 1
  • 13
  • 20
1

First thing I noticed was position:block which is actually wrong, position can basically be absolute or relative. And I strongly believe you could have put the inline styles in the .red CSS selector. To answer your question of putting the red box in front what you need is order property which has effect only on flex items so for example if you has

.green{
background: green;
order: -1;
}

The green box will be further to the left than the red box. Normally in the natural ordering all flex items has an order of zero (0) so give an item a negative other will move it further to the left until it gets to an element which is also a flex item that has a lesser order value. I noticed your red box doesn't have a height though or I omitted it accidentally while I was typing it in #happyCoding

Monday A Victor
  • 441
  • 5
  • 16