2010-11-15

DIV layering with z-index

구글맵처럼 (바닥 - 마커 - 오버레이) 등 여러 개의 레이어로 구성하고, 그 안에 위치한 각종 마커들끼리의 z-index 를 상황(?)에 따라서 코드 레벨에서 정렬해야 한다고 가정하자.

<div id="map">
  <div id="ground">
  <div id="first" class="marker">1st</div>
  <div id="second" class="marker">2nd</div>
  </div>
  <div id="overlay">
  <div id="third" class="overlay">3rd</div>
  <div id="fourth" class="overlay">4th</div>
  </div>
</div>

보통 맵은 relative, 레이어들은 absolute 로 두게 된다. 이때 레이어들의 z-index 를 지정하지 않으면(또는 auto 로 설정하면), #first 마커의 z-index 를 9999 로 잡으면 상위 레이어 위로 올라오게 된다.

#map {
  position: relative;
  width: 100%;
  height: 500px;
  background-color: gray;
}
.marker, .overlay {
  position: absolute;
  text-align: center;
}
#ground {
  position: absolute;
  left: 0;
  top: 0;
  background-color: #ededed;
  z-index: 1000;
}
#overlay {
  position: absolute;
  left: 0;
  top: 0;
  z-index: 1001;
}
#first {
  width: 100px;height: 100px;
  background-color: yellow;
}
#second {
  width: 50px;height: 200px;
  background-color: green;
}
#third {
  width: 200px;height: 50px;
  background-color: red;
}
#fourth {
  width: 50px;height: 300px;
  background-color: blue;
 }

대신 그냥 각 레이어들의 z-index 를 각각 1000,1001 로 설정하기만 하면, 아무리 하위 레이어의 마커에 높은 z-index 를 줘도, 절대 상위 레이어를 침범하지는 않게 된다.

관련 테스트 코드는 jsfiddle에서 볼 수 있다.


comments powered by Disqus