애써 HTML코드를 짜놓았는데, 어떤 엘리먼트의 position을 fixed로 바꾸었더니 화면 구성이 망가지는 경험을 자주 겪었다.
세 번째 분홍색 태그를 fixed하고 싶을 때 다음과 같은 문제가 발생한다.
<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>
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)을 가지는 태그를 이웃으로 붙이면 된다.
<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>
...
#guard {
width: 0;
height: 50px;
}
두 번째 태그의 구성이 무너지지 않고 다음과 같이 유지된다.