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

CSS로 요소의 배경 스타일 지정하는 방법

CSS에서는 background 속성을 사용하여 요소의 배경을 자유롭게 꾸밀 수 있습니다. 이 속성 하나로 배경색, 배경 이미지, 반복 방식, 위치 등 다양한 배경 관련 값을 한 번에 설정할 수 있습니다.

background 속성으로 설정할 수 있는 값

  • background-color – 요소의 배경색 지정
  • background-image – 배경으로 사용할 이미지 지정
  • background-repeat – 배경 이미지의 반복 여부 및 방식 지정
  • background-position – 배경 이미지의 위치 지정
  • background-clip – 배경이 어디까지 그려질지(클리핑 범위) 지정
  • background-size – 배경 이미지의 크기 지정
  • background-origin – 배경 이미지의 기준점(origin) 지정
  • background-attachment – 스크롤 시 배경 고정 여부 지정

기본 문법

CSS background 속성의 기본 문법은 다음과 같습니다.

Selector {
    background: /*값*/
}

예제 1: 배경색과 배경 이미지 함께 사용하기

다음 예제는 body 요소에 회색 배경과 반복되지 않는 배경 이미지를 함께 적용하는 방법을 보여줍니다.

<!DOCTYPE html>
<html>
<head>
<style>
body {
    background: gray url("https://www.tutorialspoint.com/pytorch/images/pytorch.jpg") no-repeat;
    font-size: 1.2em;
    color: black;
}
h2 {
    -webkit-text-fill-color: transparent;
    -webkit-text-stroke: 1px black;
}
p {
    box-shadow: 0 0 5px 5px black;
}
</style>
</head>
<body>
<h2><i>PYTORCH Tutorial</i></h2>
<p>This is demo text. This is demo text. This is demo text. This is demo text. This is demo text. This is demo text. This is demo text. This is demo text. This is demo text. This is demo text. This is demo text. This is demo text. This is demo text. This is demo text. This is demo text.</p>
<ul>
<li>One</li>
<li>Two</li>
<li>Three</li>
<li>Four</li>
<li>Five</li>
</ul>
</body>
</html>

실행 결과

위 코드를 실행하면 회색 배경 위에 이미지가 한 번만 표시되고, 텍스트에는 외곽선과 그림자 효과가 적용된 것을 확인할 수 있습니다.

CSS로 요소의 배경 스타일 지정하는 방법

예제 2: background-color로 배경색 지정하기

다음 예제는 h2 요소와 div 요소에 각각 다른 배경색을 적용하는 방법을 보여줍니다.

<!DOCTYPE html>
<html>
<head>
<style>
h2 {
    background-color: bisque;
}
div {
    margin: auto;
    background-color: orange;
    width: 40%;
}
</style>
</head>
<body>
<h2>Demo Text</h2>
<div>demo demo demo demo</div>
</body>
</html>

실행 결과

위 코드를 실행하면 h2 제목은 비스크(bisque) 색상의 배경을, div 영역은 주황색 배경을 가진 채 화면 중앙에 배치된 결과를 볼 수 있습니다.

CSS로 요소의 배경 스타일 지정하는 방법