1

I was just trying to make two div overlapped over each other using margin negative values...which works fine

Stack Snippet

.main {
  display: flex;
}

.item {
  width: 100px;
  height: 100px;
  background: red;
  margin-right: -20px;
}

.item:last-child {
  background: blue;
  margin-top: 20px;
}
<div class="main">
  <div class="item"></div>
  <div class="item"></div>
</div>

Now I just added the opacity:0.5 to the first item...something stranged happened. I noticed that applying opacity value less than 1 like 0.99 placing the div to front...

Updated: @Temani_Afif mentioned in the comments applying transform is giving the same effect in the first div

Stack Snippet

.main {
  display: flex;
}

.item {
  width: 100px;
  height: 100px;
  background: red;
  margin-right: -20px;
}

.item:last-child {
  background: blue;
  margin-top: 20px;
}

.item:first-child {
  transform: scale(1);
  opacity: .99;
}
<div class="main">
  <div class="item"></div>
  <div class="item"></div>
</div>

I know I can use position and z-index values to place div at front or back...

But I don't understand why applying opacity value less than 1 or or transform to first div is placing it at front...Is this a normal behavior?

Bhuwan
  • 16,525
  • 5
  • 34
  • 57
  • for the correct reference check this https://www.w3.org/TR/css-position-3/#painting-order at the point 8 – Temani Afif Feb 15 '18 at 10:05
  • and if interested in more strange behavior ;) check this one : https://stackoverflow.com/questions/48731110/strange-behavior-of-background-when-elements-are-overlapping – Temani Afif Feb 15 '18 at 10:07
  • @TemaniAfif I didn't use any `z-index` value in the `.item` class, then why `opacity` is behaving like this...didn't understand..? – Bhuwan Feb 15 '18 at 10:09
  • changing opacity create a new stacking context ... you need to read the specification in order to understand this behavior .. check the link i shared and also the dup question – Temani Afif Feb 15 '18 at 10:10
  • and if you want another trick .. replace the opacity with this `transform: translate(0,0);` and the same thing will happen ;) – Temani Afif Feb 15 '18 at 10:11
  • by the way i added more dups that are more appropriate – Temani Afif Feb 15 '18 at 10:14
  • @TemaniAfif OMG..!..now what is this?....sometimes I got the question in my mind is really HTML and CSS works like what we think..? – Bhuwan Feb 15 '18 at 10:19
  • No, HTML/CSS works like it's defined in the specification :) ... well let's say at 80% of the time is like we expect BUT for the remaining 20% everyone has his own logic in mind and may think it will behave in this way but not :) ... Did you one day think that margin can collpase ? or background of body is propagated to html when the html one is transparent ? or height:100% works only when parent height is defined ? am pretty sure no ;) .. but when you read the specification you got it and you work with it – Temani Afif Feb 15 '18 at 10:25

0 Answers0