배치 position (3) - fixed
4. fixed
fixed는 뷰포트(브라우저)를 기준으로 배치하는 배치 요소이다,
전에는 부모 요소에 static의 요소를 작성하여 자식 요소가 자신의 부모 요소를 찾다가 마지막인 뷰포트로 설정이 되는 방법이었다면 fixed는 아예 배치기준을 선언하는 배치 요소라고 할 수 있다.
그럼 이번에도 우리의 자식 2 요소를 사용하여 fixed를 설명해보겠다
.view{
background-color: royalblue;
width: 500px;
height: 300px;
position: relative;
}
.container{
background-color: tomato;
width: 300px;
height: 250px;
position: relative;
}
.container .item{
background-color: yellow;
border: 4px dashed blue;
}
.container .item:nth-child(1){
width: 100px;
height: 100px;
}
.container .item:nth-child(2){
width: 140px;
height: 70px;
position: fixed;
}
.container .item:nth-child(3){
width: 70px;
height: 120px;
}
자식 2 요소에 fixed라는 배치 요소를 작성했다.
그전에 봤던 것처럼 자식 3 요소가 순서대로 쌓여있고 자식 2요소는 자식 3요소 위에 올라와있다.
그러면 그전과는 별반 차이가 없어 보이기 때문에 자식 2 요소에 위치 값을 지정해주겠다.
(top : 20px; right: 30px;)
자식 2 요소가 뷰포트를 기준으로 입력해준 위치 값으로 이동하여 위치한 것을 볼 수 있었다.

지금은 화면을 작게 해서 저렇게 보이지만 직접 해보신다면 화면을 줄이는 거에 따라 자식 2 요소가 움직입니다.
바로 자신의 배치기준을 뷰포트로 지정했기 때문이죠!
✎ 활용 예제
그럼 fixed 사용하여 활용하는 방법을 알아보겠다.
웹페이지를 보게 되면 위에 있는 상단 내비게이션 바와 옆에 있는 배너 바가 사용자가 스크롤을 내려도 고정되어 있는 형태들을 볼 수 있다.
그럼 자식 2 요소를 fixed 배치 요소를 사용하여 설정해보겠다.
body{
height: 3000px;
}
.view{
background-color: royalblue;
width: 500px;
height: 300px;
position: relative;
}
.container{
background-color: tomato;
width: 300px;
position: relative;
}
.container .item{
background-color: yellow;
border: 4px dashed blue;
}
.container .item:nth-child(1){
width: 100px;
height: 100px;
}
.container .item:nth-child(2){
width: 140px;
height: 70px;
position: fixed;
bottom: 30px;
right: 60px;
}
.container .item:nth-child(3){
width: 70px;
height: 120px;
}
자식 2 요소가 뷰포트를 기준으로 잡고 있기 때문에
사용자가 스크롤을 올리거나 내려도 자식 2 요소는 고정되어 있는 모습을 볼 수 있다.
( ͡° ͜ʖ ͡°)
다음번에는 요소 쌓임 순서(stack order, z-index)에 대해서 알아보겠다!