Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
445 views
in Technique[技术] by (71.8m points)

css - Stacking order of elements affected by opacity

How are z-index and opacity related when deciding stacking order of an element in HTML?

when i keep opacity less than 1 on an element which is having some z-index say 999. The element is going behind the element which is having no z-index.

$(function() {
  $("#checkbox1").on("change", function() {
    $("#green-parent").toggleClass("add-opacity", this.checked);
  });
});
.green,
.blue {
  position: absolute;
  width: 100px;
  line-height: 100px;
  text-align: center;
  color: white;
}
.green {
  z-index: 999999999;
  top: 50px;
  left: 50px;
  background: green;
}
.blue {
  top: 60px;
  left: 90px;
  background: blue;
}
.add-opacity {
  opacity: 0.99;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

<input id="checkbox1" type="checkbox" value="1">
<label for="checkbox1">Add opacity to green box parent</label>


<div id="green-parent">
  <span class="green">Green</span>
</div>
<div>
  <span class="blue">Blue</span>
</div>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Aside from the opacity stacking context Alexey Ten pointed out in his comment (which is a factor here), the z-index is relative to the element's container. In this case, both your blue and green elements are contained within separate div parents which have no defined z-index. Due to the HTML ordering, the latter div (the one with the blue box) will appear on top of the former one (the green one).

In this below example, I've added the class .first to the first parent div and .second to the second one, then given them their own z-index properties.

.green, .blue {
  position: absolute;
  width: 100px;
  color: white;
  line-height: 100px;
  text-align: center;
}

.green {
  z-index:999999999;
  top: 90px;
  left: 60px;
  background: green;
}
.gp{
  opacity:0.99;
}
.blue {
  top: 100px;
  left: 100px;
  background: blue;
}

.first, .second {
  position: relative;
}

.first {
  z-index: 2;
}

.second {
  z-index: 1;
}
<div class="first">
  <span class="green">Green</span>
</div>
<div class="second">
  <span class="blue">Blue</span>
</div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...