HTML CSS

CSS background의 이해

jiyoon12 2025. 6. 16. 22:39

1. background 프로퍼티란?

background 프로퍼티는 요소의 배경을 설정하는 데 사용됩니다. 배경 색상, 이미지, 반복 방식, 위치, 크기 등을 한 번에 정의할 수 있는 단축 속성(shorthand property)입니다. 개별 속성으로도 설정 가능하며, 단축 속성을 사용하면 코드를 간결하게 작성할 수 있습니다.

 

주요 개별 속성

  • background-color: 배경 색상을 지정합니다.
  • background-image: 배경 이미지를 지정합니다.
  • background-repeat: 배경 이미지의 반복 방식을 설정합니다.
  • background-position: 배경 이미지의 위치를 설정합니다.
  • background-size: 배경 이미지의 크기를 설정합니다.
  • background-attachment: 배경 이미지의 스크롤 동작을 설정합니다.

 

2.1 background-color

  • 요소의 배경 색상을 지정합니다.
  • 값: 색상 이름(red, blue), HEX 코드(#FF0000), RGB(rgb(255, 0, 0)) 등.
  • 예: background-color: blue;

2.2 background-image

  • 배경 이미지를 설정합니다.
  • 값: url('이미지 경로')를 사용해 이미지 파일을 지정.
  • 여러 이미지를 사용할 수도 있습니다: url('이미지1'), url('이미지2').
  • 예: background-image: url('https://example.com/image.jpg');

2.3 background-repeat

  • 배경 이미지의 반복 방식을 정의합니다.
  • 값:
    • repeat: 가로/세로 모두 반복 (기본값).
    • repeat-x: 가로 방향으로만 반복.
    • repeat-y: 세로 방향으로만 반복.
    • no-repeat: 반복 없음.
    • space: 이미지가 요소에 맞게 간격을 두고 반복.
    • round: 이미지가 요소에 맞게 비율을 유지하며 반복.
  • 예: background-repeat: no-repeat;

2.4 background-position

  • 배경 이미지의 위치를 지정합니다.
  • 값:
    • 키워드: left, right, top, bottom, center.
    • 좌표: x y (예: 50% 50%, 10px 20px).
  • 예: background-position: center center;

2.5 background-size

  • 배경 이미지의 크기를 설정합니다.
  • 값:
    • auto: 원본 크기 (기본값).
    • length: 특정 크기 (예: 100px 200px).
    • cover: 요소를 덮도록 크기 조정 (비율 유지, 잘림 가능).
    • contain: 요소 안에 맞도록 크기 조정 (비율 유지, 빈 공간 가능).
  • 예: background-size: cover;

2.6 background-attachment

  • 배경 이미지의 스크롤 동작을 설정합니다.
  • 값:
    • scroll: 요소와 함께 스크롤 (기본값).
    • fixed: 뷰포트에 고정, 스크롤 시 움직이지 않음.
  • 예: background-attachment: fixed;

2.7 단축 속성 background

  • 위 속성들을 한 줄로 정의할 수 있습니다.
  • 순서: background: color image repeat attachment position/size;
  • 예: background: yellow url('image.jpg') no-repeat fixed center/cover;

 

  • background 의 여러 속성들 실습

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        .box {
            width: 100%;
            height: 300px;
            background-color: lightblue;
            background-image: url('https://picsum.photos/200/300');
            /* 배경 이미지 반복 설정 */
            background-repeat: no-repeat;
            /* 앞이 상하, 뒤가 좌우  */
            background-position: center center;
        }
        
    </style>
</head>
<body>
    
    <div class="box">
        <h2>배경 이미지 예제</h2>
        <p>배경 이미지가 중앙에 위치하며 반복되지 않습니다</p>
    </div>
</body>
</html>