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

CSS 배경 위치(background-position) 완벽 가이드

웹 페이지에서 배경 이미지의 위치를 조절하고 싶다면 background-position 속성을 사용하면 됩니다. 이 속성은 배경 이미지가 표시되기 시작하는 위치, 즉 시작 지점을 지정하는 역할을 합니다.

background-position 속성은 키워드(left, right, top, bottom, center)뿐만 아니라 백분율(%)이나 픽셀(px) 값으로도 지정할 수 있어 매우 유연하게 활용할 수 있습니다.

예제 1: 키워드로 위치 지정하기

아래 예제에서는 left center 값을 사용하여 배경 이미지를 화면 왼쪽 중앙에 배치합니다.

<!DOCTYPE html>
<html>
<head>
<style>
body {
   background-image: url("https://www.tutorialspoint.com/images/Swift.png");
   background-repeat: no-repeat;
   background-attachment: fixed;
   color: blue;
   background-position: left center;
}
.demo {
   text-decoration: overline underline;
}
</style>
</head>
<body>
<h1>Details</h1>
<p class="demo">Examination Center near ABC College.</p>
<p class="demo2">Exam begins at 9AM.</p>
</body>
</html>

실행 결과

CSS 배경 위치(background-position) 완벽 가이드

예제 2: 백분율로 위치 지정하기

이번에는 50% 50% 값을 사용하여 배경 이미지를 화면 정중앙에 배치해 보겠습니다. 첫 번째 값은 가로 방향, 두 번째 값은 세로 방향 위치를 의미합니다.

<!DOCTYPE html>
<html>
<head>
<style>
body {
   background-image: url("https://www.tutorialspoint.com/images/Swift.png");
   background-repeat: no-repeat;
   background-attachment: fixed;
   color: blue;
   background-position: 50% 50%;
}
</style>
</head>
<body>
<h1>Details</h1>
<p>Examination Center near ABC College.</p>
<p>Exam begins at 9AM.</p>
</body>
</html>

실행 결과

CSS 배경 위치(background-position) 완벽 가이드

정리

background-position 속성은 다음과 같은 다양한 값을 지원합니다.

  • 키워드 값: left, right, top, bottom, center를 조합하여 사용 (예: left center)
  • 백분율 값: 요소 크기 기준으로 위치 지정 (예: 50% 50%)
  • 길이 값: 픽셀(px), em 등 절대 단위로 정밀하게 지정 가능

일반적으로 background-position은 background-repeat: no-repeat와 함께 사용되며, 배경 이미지가 반복되지 않도록 설정한 후 원하는 위치에 한 번만 표시하는 방식으로 활용됩니다.