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

CSS background-image 속성으로 배경 이미지 설정하기

CSS의 background-image 속성은 HTML 요소의 배경에 이미지를 지정할 때 사용합니다. 이 속성에 url() 함수를 통해 이미지 경로를 전달하면, 해당 요소의 배경이 지정한 이미지로 채워집니다.

기본 문법

selector {
  background-image: url("이미지 경로");
}

이미지 경로는 절대 URL 또는 상대 경로 모두 사용할 수 있습니다.

예제

다음 코드를 실행하면 빨간색 점선 테두리가 있는 div 요소 안에 배경 이미지가 적용되는 것을 확인할 수 있습니다.

<html>
   <head>
      <style>
         #demo {
            border: 5px dashed red;
            padding: 10px;
            background-image: url("https://www.tutorialspoint.com/css/images/css-mini-logo.jpg");
         }
      </style>
   </head>
   <body>
      <div id="demo">
         <h1>www.tutorialspoint.com</h1>
         <p>Tutorials Point originated from the idea that there exists a class of readers who respond better to online content and prefer to learn new skills at their own pace from the comforts of their drawing rooms.</p>
      </div>
   </body>
</html>

코드 설명

  • border: 5px dashed red; — 요소에 두께 5px의 빨간색 점선 테두리를 적용합니다.
  • padding: 10px; — 콘텐츠와 테두리 사이에 10px의 여백을 줍니다.
  • background-image: url(...); — 지정한 이미지 파일을 해당 div의 배경으로 설정합니다.

함께 알아두면 좋은 배경 관련 속성

배경 이미지를 더 세밀하게 제어하려면 아래 속성들을 함께 사용하는 것이 좋습니다.

  • background-repeat: 이미지 반복 여부를 설정합니다. (repeat, no-repeat, repeat-x, repeat-y)
  • background-size: 이미지 크기를 조절합니다. (cover, contain, 픽셀 또는 백분율 값)
  • background-position: 이미지의 위치를 지정합니다. (center, top, left 등)

여러 배경 속성을 한 번에 선언하려면 축약형 속성인 background를 사용할 수도 있습니다.