프론트엔드/Tips

position:fixed와 transform

Marshall K 2019. 5. 7. 01:28

결론부터 간단히 짚고 넘어가자면, transform으로 위치를 옮긴 요소의 자식은 position: fixed를 써도 고정되지 않습니다.


https://www.w3.org/TR/css-transforms-1/#transform-rendering

여기서 상세한 설명을 읽으실 수 있습니다.



요소에 배경을 넣으면 글자가 읽기 힘들어져서, 전 보통 이미지의 opacity를 낮추고 배경을 검은색으로 만든 뒤, 글자를 흰색으로 변경합니다.

그때, background-image의 opacity 조절을 위해 새 자식 요소를 만들고, 그 요소의 opacity를 조절합니다.


이번에 드로워의 배경도 똑같이 만들다 문제에 봉착했는데, 드로워를 스크롤 하면 자식 요소에 부여한 position: fixed가 position: absolute인 양 작동한단 겁니다.


해결을 위해, 배경 이미지가 들어갈 요소를 밖으로 뺀 뒤, 드로워와 똑같은 상황에서 똑같이 움직여 마치 한 요소인 것처럼 보이게 했습니다.


<nav id="Leftnav" class="simplebar">
<!-- Something -->
</nav>
<div id="LeftBG">
<div style="background-image:url()" class="bg reveal"></div>
<div style="background-image:url()" class="bg"></div>
<div style="background-image:url()" class="bg"></div>
</div>


#Leftnav {
position: fixed;
top: 0;
visibility: hidden;
opacity: 0;
width: 400px;
height: 100%;
max-width: 100%;
z-index: 2000;
background: rgba(0, 0, 0, .5);
color: #fff;
transition: .5s
}

#Leftnav,
#LeftBG {
left: 0;
transform: translateX(-400px)
}

#LeftBG {
position: fixed;
width:400px;
height:100%;
background: #000;
opacity: 0;
z-index: 1995
}

.navrevealed #Leftnav,
.navrevealed #LeftBG {
opacity: 1;
visibility: visible;
transform: translateX(0)
}

#LeftBG .bg {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
opacity: .5;
background-size: cover;
background-position: center;
background-repeat: no-repeat;
}


드로워와 배경은 같은 조건에서 같이 움직이며, 드로워엔 반투명한 검은 배경을, 배경에도 적당한 투명도 조절을 해서 드로워의 배경처럼 보이게 했습니다.