css - position: fixed 사용 시 팁

BigbrotherShin·2020년 4월 30일
0

html, css

목록 보기
1/1
post-thumbnail

문제 상황

애써 HTML코드를 짜놓았는데, 어떤 엘리먼트의 position을 fixed로 바꾸었더니 화면 구성이 망가지는 경험을 자주 겪었다.

세 번째 분홍색 태그를 fixed하고 싶을 때 다음과 같은 문제가 발생한다.

index.html

<html>
 <head>
    <title>position: fixed 꿀팁</title>
    <link rel="stylesheet" href="style.css">
 </head>
 <body>
   <div id="first">
     첫 번째 태그
     <div id="second">
       두 번째 태그
       <div id="third">
         세 번째 태그
       </div>
     </div>
   </div>
   <script src="src/index.js"></script>
 </body>
</html>

style.css

div {
  padding: 10px;
}

#fitst {
  background: skyblue;
  height: 150px;
}

#second {
  background: greenyellow;
}

#third {
  background: orchid;
  height: 50px;
}

기본 값(position: static)일 때에는 두 번째 태그의 height는 세 번째 태그의 height: 50px 만큼 더 늘어난다.

망가져 버린 구성

여기에서 세 번째 태그에 position: fixed를 추가하는 경우 부모 태그와의 관계가 끊어지게 되어 세 번째 태그의 height: 50px이 빠지게 되어 두 번째 태그가 작아지게 된다.

해결 방법

width: 0이고 height가 fixed할 태그(세 번째 태그)와 같은 값(예제에서는 height: 50px)을 가지는 태그를 이웃으로 붙이면 된다.

index.html

<html>
 <head>
    <title>position: fixed 꿀팁</title>
    <link rel="stylesheet" href="style.css">
 </head>
 <body>
   <div id="first">
     첫 번째 태그
     <div id="second">
       두 번째 태그
       <div id="third">
         세 번째 태그
       </div>
       <div id="guard"></div> // 새로 붙여준 태그
     </div>
   </div>
   <script src="src/index.js"></script>
 </body>
</html>

styles.css

...

#guard {
  width: 0;
  height: 50px;
}

두 번째 태그 보존

두 번째 태그의 구성이 무너지지 않고 다음과 같이 유지된다.

참고: css의 position 속성을 알아봅시다.

profile
JavaScript, Node.js 그리고 React를 배우는

0개의 댓글