Computer >> 컴퓨터 >  >> 프로그래밍 >> CSS

CSS position: fixed로 요소 고정하기 – 고정 위치 지정 완벽 정리

CSS에서 요소의 위치 지정 방식을 fixed(고정)로 설정하면 해당 요소는 사용자의 뷰포트(viewport)를 기준으로 배치됩니다. fixed로 지정된 요소는 페이지를 스크롤해도 화면상에서 움직이지 않으며, CSS 위치 속성인 left, right, top, bottom을 사용해 원하는 위치에 배치할 수 있습니다.

이러한 특성 덕분에 fixed 포지셔닝은 상단 내비게이션 바, 플로팅 버튼, 사이드 광고 배너처럼 항상 화면에 고정되어 있어야 하는 UI 요소를 만들 때 널리 활용됩니다.

예제 1: 기본적인 fixed 위치 지정

다음은 CSS 고정 위치 지정 방식을 보여주는 예제입니다.

<!DOCTYPE html>
<html>
<head>
<style>
p {
    margin: 0;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}
div:first-child {
    background-color: orange;
    text-align: center;
}
div:last-child {
    width: 250px;
    height: 100px;
    margin: auto;
    background-color: turquoise;
    position: absolute;
    z-index: -1;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
}
</style>
</head>
<body>
<div>What is ASP.NET?</div>
<p>ASP.NET is a web application framework developed and marketed by Microsoft to allow programmers to build dynamic web sites............</p>
<div>
</div>
</body>
</html>

실행 결과

위 코드를 실행하면 다음과 같은 결과가 출력됩니다.

CSS position: fixed로 요소 고정하기 – 고정 위치 지정 완벽 정리

예제 2: relative, absolute, fixed 비교

이번에는 세 가지 위치 지정 방식(relative, absolute, fixed)의 차이를 한눈에 비교할 수 있는 예제를 살펴보겠습니다.

<!DOCTYPE html>
<html>
<head>
<style>
div {
    border: 2px double #a43356;
    margin: 5px;
    padding: 5px;
}
#d1 {
    position: relative;
    height: 10em;
}
#d2 {
    position: absolute;
    width: 20%;
    bottom: 10px; /* 부모 요소 d1 기준 */
}
#d3 {
    position: fixed;
    width: 30%;
    top: 10em; /* 뷰포트 기준 */
}
</style>
</head>
<body>
<div id="d1">Android is an open source and Linux-based operating system for mobile devices such as smartphones and tablet computers. Android was developed by the Open Handset Alliance, led by Google, and other companies. <mark>relative</mark>
<div id="d2"><mark>absolute</mark></div>
<div id="d3"><mark>fixed</mark></div>
</div>
</body>
</html>

실행 결과

위 코드를 실행하면 다음과 같은 결과가 출력됩니다.

CSS position: fixed로 요소 고정하기 – 고정 위치 지정 완벽 정리

정리

  • fixed: 뷰포트를 기준으로 요소를 배치하며, 스크롤과 무관하게 항상 같은 화면 위치에 고정됩니다.
  • absolute: position 속성이 static 이외의 값으로 설정된 가장 가까운 조상 요소를 기준으로 배치됩니다.
  • relative: 요소의 원래 위치를 기준으로 상대적으로 이동시키며, 자식 absolute 요소의 기준점 역할도 합니다.

fixed 포지셔닝을 활용하면 스크롤해도 사라지지 않는 고정 헤더, 하단 바, 팝업 버튼 등 다양한 사용자 인터페이스를 손쉽게 구현할 수 있습니다.