개요
웹 사이트의 UI를 본격적으로 만들기 시작하면서 요소의 상대적인 위치에 대해 적용하기 위해서는 CSS에 포지셔닝에 대해 알아야 할 필요성을 느끼고 있다.
1. position 속성
CSS에서 position은 요소의 위치를 어떻게 지정할지를 정하는 속성이다.
이 속성 값에는 static, relative, absolute, fixed, sticky가 있는데 각각의 속성에 대해 알아봅시다.
//GridBlock.css
.grid {
display: grid;
grid-template-columns: repeat(3, 100px);
grid-template-rows: repeat(3, 100px);
gap: 4px;
width: max-content;
background-color: white;
padding: 4px;
}
.cell {
background-color: #ccc;
}
.center {
background-color: #2dfbc4;
}
.yellow-square {
top: 0;
left: 0;
width: 25px;
height: 25px;
background-color: rgb(255, 247, 0);
}
className center가 저 가운데 있는 초록색이고, yellow-square는 저 노란색이다.
이 코드를 기준으로 정리해 나가겠다.
1-1. static (기본값)
position을 따로 지정하지 않으면 자동으로 static이 된다.
이때는 기존의 문서 흐름(= 일반적인 DOM 순서)을 따르기 때문에 top, left, right, bottom, z-index 등의 위치 속성을 지정하더라도 무시된다.
.center {
background-color: #2dfbc4;
top: 40px;
left: 40px;
}
-> center에 top : 40px, left : 40px을 적용하더라도 화면은 그대로이다.
1-2. relative
relative 속성은 현재 자기 위치를 기준으로 이동하며, 공간을 차지한다.
.center {
position: relative;
background-color: #2dfbc4;
top: 20px;
left: 20px;
}
-> 저 초록색 네모에 position을 relative로 지정해주고 top과 left를 각각 20px 씩 적용했더니 가운데 있던애가 지정해 준 거리만큼 이동했다.
1-3. absolute
static이 아닌 첫 부모 요소를 기준으로 위치를 조정할 수 있다. 또한 자리를 차지하지 않는다!
.grid {
position: relative;
display: grid;
grid-template-columns: repeat(3, 100px);
grid-template-rows: repeat(3, 100px);
gap: 4px;
background-color: white;
padding: 4px;
}
.center {
background-color: #2dfbc4;
top: 30px;
left: 20px;
}
.yellow-square {
position: absolute;
top: 20px;
left: 20px;
width: 25px;
height: 25px;
background-color: rgb(255, 247, 0);
}
-> grid에는 relative 속성을 주고, center에는 기본값인 static, yellow-square에 absolute 속성을 줬다.
-> 이때 yellow-square의 부모인 center가 static이기 때문에 static이 아닌 첫 부모 grid에게 맞춰 top, left가 이동되는 것을 알 수 있다.
1-4. fixed
부모 요소가 아닌 뷰포트를 기준으로 위치를 지정할 수 있다.
.yellow-square {
position: fixed;
top: 20px;
left: 20px;
width: 25px;
height: 25px;
background-color: rgb(255, 247, 0);
}
-> yellow-square의 position 속성을 fixed로 지정했더니
-> 브라우저 화면 기준으로 위치가 지정됐다.
fixed는 또한 스크롤에 영향을 받지 않는데, 스크롤을 내려도 고정된 위치에서 요소가 절대 움직이지 않는다. 팝업이나 배너에 유용하겠지?
1-5. sticky
스크롤 위치에 따라서 relative처럼 있다가도, 특정 지점에 도달하면 fixed처럼 동작한다.
.center {
position: sticky;
top: 20px;
background-color: #2dfbc4;
}
-> center에 sticky 속성을 주고 top에 20px를 줬는데
-> 스크롤 전에 이렇게 있다가
-> 스크롤이 끝날때까지 브라우저 기준 top 20px 떨어진 정도로 계속 유지된다.
'Language > HTML&CSS' 카테고리의 다른 글
[CSS] px, em, rem 차이점 (0) | 2025.03.31 |
---|---|
[CSS] Flexbox란? (0) | 2025.02.18 |
[CSS] 박스 모델 (0) | 2025.02.18 |
[CSS] 인라인과 블록 (0) | 2025.02.17 |
[CSS] CSS 적용 방법, 선택자, 결합자, 가상 클래스 (0) | 2025.02.03 |