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

CSS background-size 속성으로 배경 이미지 크기 지정하기

CSS의 background-size 속성은 배경 이미지(background-image)의 크기를 지정하는 데 사용됩니다. 이 속성을 활용하면 원본 이미지의 크기나 비율과 상관없이 원하는 픽셀 값 또는 백분율로 배경 이미지의 가로·세로 크기를 자유롭게 조절할 수 있습니다.

background-size 속성의 주요 값

  • 픽셀(px) 등 단위 값 — 가로와 세로 크기를 직접 지정합니다. 예: background-size: 200px 100px;
  • 백분율(%) — 해당 요소를 기준으로 이미지 크기를 상대적으로 설정합니다.
  • cover — 배경 영역을 완전히 덮도록 이미지를 확대·축소합니다. 필요에 따라 이미지 일부가 잘릴 수 있습니다.
  • contain — 이미지 전체가 잘리지 않고 보이도록 배경 영역 안에 맞춥니다.

예제 코드

아래 예제는 background-size 속성을 사용해 배경 이미지의 크기를 가로 200px, 세로 100px로 지정한 사례입니다. 초록색 점선 테두리가 있는 div 요소 안에 배경 이미지가 설정된 크기로 표시됩니다.

<html>
   <head>

      <style>
         #demo {
            border: 5px dashed green;
            padding: 10px;
            background-image: url("https://www.tutorialspoint.com/css/images/css-mini-logo.jpg");
            background-size: 200px 100px;
         }
      </style>

   </head>
   <body>

      <div id="demo">
         <h1>www.tutorialspoint.com</h1>
         <p>The website www.tutorialspoint.com is owned and maintained by Tutorials Point India Private Limited,
            henceforth termed as “we”, “our”, “us”, or the “company”. All the visitors, users, learners, contributors,
            teachers, and instructors are named as "users"; and the website tutorialspoint.com is termed as "website" everywhere in this document.
            We are committed to protecting your privacy online. This privacy policy explains what information we collect from you
            or what information you share with us when you visit the website. We review our policy from time to time, so you are advised to check the latest version.</p>
      </div>
   </body>
</html>

코드 설명

  • border: 5px dashed green; — 요소에 초록색 점선 테두리를 추가하여 배경 이미지 영역을 시각적으로 구분합니다.
  • padding: 10px; — 콘텐츠와 테두리 사이에 여백을 줍니다.
  • background-image — 지정한 URL의 이미지를 배경으로 설정합니다.
  • background-size: 200px 100px; — 배경 이미지를 가로 200픽셀, 세로 100픽셀 크기로 조정합니다.

위 코드를 브라우저에서 실행하면 배경 이미지가 지정된 크기로 표시되는 것을 확인할 수 있습니다. 반응형 웹 디자인에서는 고정 픽셀 대신 %, cover, contain 값을 사용하는 것이 더 유연한 결과를 제공합니다.