배경 이미지 넣기
background-image는 요소의 콘텐츠, padding, 테두리 뒤에 이미지를 그려요. 기본적으로 padding 상자의 왼쪽 위 모서리에서 시작하고, 원래 크기를 유지하며, 상자를 채우도록 반복돼요.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Background image</title>
<style>
body { font-family: system-ui, sans-serif; }
.dots {
/* a 24x24 image: one blue dot */
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24'%3E%3Ccircle cx='12' cy='12' r='4' fill='%232563eb'/%3E%3C/svg%3E");
height: 120px;
padding: 16px;
border: 2px solid #111827;
font-weight: 600;
}
</style>
</head>
<body>
<div class="dots">One 24px image, repeated to fill the box</div>
</body>
</html>Master CSS the hands-on way
Interactive lessons, real projects, and instant feedback.
START NOW
실제 프로젝트에서는 url()이 파일을 가리켜요. url("images/hero.jpg")처럼요. 경로는 그 코드가 들어 있는 스타일시트 기준이에요(<style> 요소라면 페이지 기준). 이 페이지의 예제는 어디서든 실행되도록 작은 SVG 이미지를 data: URL로 직접 적었어요.
처음부터 알아 둘 두 가지가 있어요.
배경은 요소에 크기를 주지 않아요. 배경 이미지가 있는 빈 div의 높이는 0px이에요. 콘텐츠, padding, height, aspect-ratio 중 하나를 주세요.
배경 이미지는 장식이에요. 스크린 리더는 건너뛰고, 대체 텍스트도 없어요. 의미를 담은 이미지는 <img> 요소에 넣어야 해요.
background-size: cover, contain, 길이
background-size는 이미지 크기를 조절해요. 두 키워드는 비율을 유지해요.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>cover vs contain</title>
<style>
body { font-family: system-ui, sans-serif; font-size: 14px; }
.row { display: flex; gap: 12px; flex-wrap: wrap; }
.box {
--landscape: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='400' height='200' viewBox='0 0 400 200'%3E%3Crect width='400' height='200' fill='%23bfdbfe'/%3E%3Ccircle cx='320' cy='50' r='24' fill='%23f59e0b'/%3E%3Cpath d='M0 200L120 70L220 200Z' fill='%2316a34a'/%3E%3Cpath d='M140 200L270 90L400 200Z' fill='%2315803d'/%3E%3C/svg%3E");
width: 160px; height: 160px;
background: var(--landscape) center / auto no-repeat, #e5e7eb;
border: 2px solid #111827;
}
.cover { background-size: cover; }
.contain { background-size: contain; }
.stretch { background-size: 100% 100%; }
</style>
</head>
<body>
<div class="row">
<div><div class="box"></div>auto (400x200, cropped)</div>
<div><div class="box cover"></div>cover</div>
<div><div class="box contain"></div>contain</div>
<div><div class="box stretch"></div>100% 100% (distorted)</div>
</div>
</body>
</html>
이미지는 너비가 높이의 두 배이고, 각 상자는 정사각형이에요.
값 결과 auto (기본값)이미지 원래 크기 cover상자가 완전히 찰 때까지 키우고, 넘치는 부분은 잘려요 contain이미지 전체가 들어갈 때까지 키우고, 두 변에 회색 띠가 남아요 200px너비 200px, 높이는 비율에 맞게 50% auto상자 너비의 절반, 높이는 비율에 맞게 100% 100%정확히 상자 크기. 비율이 다르면 이미지가 찌그러져요
히어로 배너와 카드에는 보통 cover를 골라요. contain은 절대 잘리면 안 되는 로고와 일러스트용이에요.
background-position과 background-repeat
background-position은 키워드(top, center, bottom, left, right), 퍼센트, 길이로 상자 안에서 이미지 위치를 정해요. background-repeat는 반복을 제어해요. 값을 넣어 보세요.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Position and repeat</title>
<style>
body { font-family: system-ui, sans-serif; }
#box {
height: 140px; margin-top: 10px;
border: 2px solid #111827;
background-color: #f3f4f6;
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24'%3E%3Ccircle cx='12' cy='12' r='4' fill='%232563eb'/%3E%3C/svg%3E");
background-size: 48px;
}
label { display: block; margin-top: 6px; }
</style>
</head>
<body>
<label>background-position: <input id="pos" value="center" size="18"></label>
<label>background-repeat: <input id="rep" value="no-repeat" size="18"></label>
<div id="box"></div>
<script>
const box = document.getElementById('box');
const pos = document.getElementById('pos');
const rep = document.getElementById('rep');
const show = () => {
box.style.backgroundPosition = pos.value;
box.style.backgroundRepeat = rep.value;
};
pos.addEventListener('input', show);
rep.addEventListener('input', show);
show();
</script>
</body>
</html>
위치에는 top right, bottom 10px right 20px, 25% 75%를, 반복에는 repeat-x, repeat-y, space(잘리는 타일이 없도록 틈을 두고 반복), round(정수 개가 들어가도록 타일 크기를 조절)를 넣어 보세요.
레이어: 여러 배경과 텍스트 오버레이
background-image는 쉼표로 구분한 목록을 받아요. 첫 번째 레이어가 맨 위에 그려져요. 흔한 용도는 사진 위에 반투명 그라데이션을 올려 흰 텍스트를 읽기 좋게 하는 거예요.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Overlay</title>
<style>
body { font-family: system-ui, sans-serif; margin: 0; }
.hero {
--landscape: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='400' height='200' viewBox='0 0 400 200'%3E%3Crect width='400' height='200' fill='%23bfdbfe'/%3E%3Ccircle cx='320' cy='50' r='24' fill='%23f59e0b'/%3E%3Cpath d='M0 200L120 70L220 200Z' fill='%2316a34a'/%3E%3Cpath d='M140 200L270 90L400 200Z' fill='%2315803d'/%3E%3C/svg%3E");
background-image:
linear-gradient(rgb(17 24 39 / 10%), rgb(17 24 39 / 75%)),
var(--landscape);
background-size: cover;
background-position: center;
aspect-ratio: 16 / 7;
display: flex; align-items: end;
padding: 20px; box-sizing: border-box;
color: white;
}
h1 { margin: 0; font-size: 32px; }
</style>
</head>
<body>
<div class="hero" id="hero"><h1>Readable over an image</h1></div>
</body>
</html>
aspect-ratio가 빈 상자에 높이를 주고, background-size: cover는 두 레이어 모두에 적용돼요. 그라데이션 예제가 더 필요하면 CSS 그라데이션 을 보세요.
background 단축 속성
background는 모든 배경 속성을 한 줄로 정해요. size는 position 바로 뒤에 슬래시로 구분해서 오고, 색은 마지막 레이어에 들어가요.
.hero {
background: url("hero.jpg") center / cover no-repeat, #1f2937;
}
/* the same as */
.hero {
background-image: url("hero.jpg");
background-position: center;
background-size: cover;
background-repeat: no-repeat;
background-color: #1f2937;
}
대체 색은 이미지가 로드되는 동안, 그리고 로드에 실패했을 때 보여요. 단축 속성에서 빠뜨린 속성은 모두 기본값으로 초기화되니, 단축 속성을 먼저 쓰고 개별 속성을 그 뒤에 쓰세요.
다른 배경 속성들
속성 하는 일 background-attachment: fixed페이지를 스크롤해도 이미지가 제자리에 있어요(iOS Safari에서는 무시돼요) background-origin위치가 border, padding, content 중 어느 가장자리에서 시작하는지 background-clip배경을 칠하는 범위, 글자를 채우는 text 포함 background-blend-modemultiply처럼 레이어를 섞어요
자주 하는 실수
잘못된 경로. 스타일시트의 url()은 HTML 페이지가 아니라 CSS 파일 기준이에요.
빈 요소. 높이가 없어서 이미지가 보일 곳이 없어요.
contain이나 작은 이미지에 no-repeat 빠뜨리기. 타일처럼 반복돼요.
cover를 뜻했는데 100% 100%로 늘리기.
중요한 이미지를 배경으로 쓰기. 콘텐츠는 대체 텍스트가 있는 <img>를 쓰세요. 배경은 스크린 리더에 보이지 않아요.
공백이나 따옴표가 든 data: URL에 따옴표 빠뜨리기. 항상 url("...")로 쓰세요.