CSS

[CSS] flex자식 요소인 경우, sticky가 안먹힐때

tailwind가 적용된 게시글입니다. 하지만 tailwind 모르셔도 쉽게 유추 가능합니다.

 

❌ 문제 코드

<div class="mt-8 flex justify-between gap-3">
	<div></div>
	<aside class="sticky top-0 "></aside>
</div>

위 코드에서 aside태그의 sticky가 정상적으로 먹히지 않았다. 

 

 

 

🔍 원인

flex는 기본적으로 `align-items: stretch`이 적용된다.

align-items: stretch란?

출처: 1분 코딩

flex내부의 아이템들을 수직으로 쭉~ 늘어지게 하는 것이다.

 

sticky는 부모영역 내에서 본인의 위치가 고정되는 것인데, flex 의 align-items: stretch로 본인 영역 과 부모영역의 높이가 같아진 것이다. 그래서 정상적으로 작동하지 않는 것.

 

 

 

🍀 해결

이를 해결하기 위해서는 해당 자식요소는 부모 flex 의 `align-items: stretch`가 적용되지 않도록 해야한다.

 

이때 필요한 게, align-self

`flex`의 item들은 기본적으로 align-items 설정을 상속 받는다. 하지만 `align-self`는 `align-items`보다 우선권이 있다.

 

부모 - `align-items`

자식 - `align-self`

이렇게 생각하면 편하다.

 

sticky하려는 요소에 `align-self: flex-start`를 추가해주자
.sticky {
  position: -webkit-sticky; /* for Safari */
  position: sticky;
  top: 0;
  align-self: flex-start; /* <-- this is the fix */
}
728x90
반응형