CSS flexbox z-index 層疊關係

需求:

父項有兩個子項,要進行層疊

要點:

當元素的position設定absolute後,它就會往外層的元素找是否有position:relative | absolute | fixed | inherit(若繼承的是前面3個之一)的元素,若是都沒有,就會以該網頁頁面(<body>)的左上角為定位點。

z-index 越大越前

實作:

content 底下有 back, front 兩同層級元素,有層疊關係

content 設置 position: relative;

back 設置 position: absolute; 與 z-index = -1;

front 設置 position: absolute; 與 z-index = 1;

<div class="content">
  <div class="back"></div>
  <div class="front"></div>
</div>

<style>
.content {
  display: flex;
  position: relative;
}

.back{
  height: 10rem;
  width: 10rem;
  z-index: -1;
  position: absolute;
  background-color: red;
}

.front{
  height: 5rem;
  width: 5rem;
  z-index: 1;
  position: absolute;
  background-color: blue;
}
</style>

References

https://ithelp.ithome.com.tw/articles/10212202

https://blog.towavephone.com/css-world-stacking-rule/


comments powered by Disqus