06_swiper
코드 블록의 Try it Yourself 버튼으로 직접 실행할 수 있다.
구문
1. Swiper란?
📝NOTE
Swiper 공식 사이트
Swiper는 터치 슬라이더 라이브러리. 모바일과 데스크톱 모두 지원.
주요 특징:
- 터치/드래그 지원
- 반응형 디자인
- 다양한 효과 (fade, cube, flip 등)
- 네비게이션, 페이지네이션 지원
2. 설치
2.1. CDN
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/swiper@11/swiper-bundle.min.css" />
<script src="https://cdn.jsdelivr.net/npm/swiper@11/swiper-bundle.min.js"></script>
2.2. NPM
npm install swiper
3. 기본 구조
:::tip[필수 구조] 슬라이드는 반드시 두 단계로 감싸야 합니다. :::
<div class="swiper">
<div class="swiper-wrapper">
<div class="swiper-slide">슬라이드 1</div>
<div class="swiper-slide">슬라이드 2</div>
<div class="swiper-slide">슬라이드 3</div>
</div>
<div class="swiper-pagination"></div>
<div class="swiper-button-prev"></div>
<div class="swiper-button-next"></div>
</div>
4. 주요 옵션
| 파라미터 | 설명 | 타입/값 예시 | 기본값 |
|---|---|---|---|
loop | 무한 반복 | true / false | false |
autoplay | 자동 재생 | { delay: 3000 } / false | false |
speed | 전환 속도(ms) | 300, 1000 | 300 |
slidesPerView | 보여줄 슬라이드 수 | 1, 2, auto | 1 |
spaceBetween | 슬라이드 간격(px) | 0, 20 | 0 |
direction | 슬라이드 방향 | horizontal / vertical | horizontal |
effect | 전환 효과 | slide, fade, cube 등 | slide |
centeredSlides | 활성 슬라이드 중앙 배치 | true / false | false |
autoHeight | 자동 높이 조절 | true / false | false |
pagination | 페이지네이션 설정 | { el: '.swiper-pagination' } | 없음 |
navigation | 이전/다음 버튼 설정 | { nextEl, prevEl } | 없음 |
breakpoints | 반응형 설정 | { 640: {...}, ... } | 없음 |
on | 이벤트 핸들러(콜백) | { slideChange: fn } | 없음 |
6. 단계별 예제
6.1. STEP 1: 기본 슬라이더
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>기본 Swiper</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/swiper@11/swiper-bundle.min.css">
<style>
.swiper {
width: 100%;
height: 300px;
}
.swiper-slide {
background: #eee;
display: flex;
align-items: center;
justify-content: center;
font-size: 24px;
}
</style>
</head>
<body>
<div class="swiper">
<div class="swiper-wrapper">
<div class="swiper-slide">1</div>
<div class="swiper-slide">2</div>
<div class="swiper-slide">3</div>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/swiper@11/swiper-bundle.min.js"></script>
<script>
const swiper = new Swiper('.swiper', {
loop: true
});
</script>
</body>
</html>
6.2. STEP 2: 네비게이션 & 페이지네이션 추가
:::tip[필수 구조]
.swiper-pagination, .swiper-button-prev, .swiper-button-next 는 반드시 .swiper-wrapper 와 형제요소로 삽입 합니다.
:::
<div class="swiper">
<div class="swiper-wrapper">
<div class="swiper-slide">1</div>
<div class="swiper-slide">2</div>
<div class="swiper-slide">3</div>
</div>
<div class="swiper-pagination"></div>
<div class="swiper-button-prev"></div>
<div class="swiper-button-next"></div>
</div>
<script>
const swiper = new Swiper('.swiper', {
loop: true,
// 페이지네이션 설정
pagination: {
el: '.swiper-pagination',
clickable: true
},
// 네비게이션 설정
navigation: {
nextEl: '.swiper-button-next',
prevEl: '.swiper-button-prev'
}
});
</script>
6.3. STEP 3: 자동 재생
const swiper = new Swiper('.swiper', {
loop: true,
autoplay: {
delay: 3000, // 3초마다 전환
disableOnInteraction: false,// 사용자 조작 후에도 자동재생 유지
pauseOnMouseEnter: true // 마우스 올리면 일시 정지 (핵심 설정)
},
pagination: {
el: '.swiper-pagination',
clickable: true
}
});
6.4. STEP 4: 여러 슬라이드 보이기
const swiper = new Swiper('.swiper', {
slidesPerView: 3, // 한 번에 3개 보이기
spaceBetween: 20, // 슬라이드 간격 20px
centeredSlides: true, // 활성 슬라이드 중앙 배치
loop: true
});
6.5. STEP 5: 반응형 설정
const swiper = new Swiper('.swiper', {
slidesPerView: 1, // 기본 (모바일)
spaceBetween: 10,
// 화면 크기별 설정
breakpoints: {
// 640px 이상
640: {
slidesPerView: 2,
spaceBetween: 20
},
// 768px 이상
768: {
slidesPerView: 3,
spaceBetween: 30
},
// 1024px 이상
1024: {
slidesPerView: 4,
spaceBetween: 40
}
}
});
6.6. 기타 예제
7. 이미지 갤러리 예제
swiper를 이용해 이미지갤러리를 제작한다. 가로 820픽셀 이미지 8 장을 준비하고 Swiper를 이용해서 3개의 이미지가 보여지며 페이지 이동과 이전, 다음 버튼을 이용해 이미지를 변경할 수 있도록 제작
7.1. STEP1
- reset.css 와 스와이퍼를 설치한다
html <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,GRAD@24,400,0,0" /> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/reset-css@5.0.1/reset.min.css" /> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/swiper@11/swiper-bundle.min.css" /> <script src="https://cdn.jsdelivr.net/npm/swiper@11/swiper-bundle.min.js" defer></script>- section 태그 자식요소로 div 를 만들고 자식요소로 스와이퍼 요소를 추가한다. 스와이퍼에서 제공하는 클래스이름은 변경하지 않고 그대로 사용한다. 스와이퍼의 부모요소인 section과 div 는 필요에 따라 변경해서 사용하면된다.
<section class="notice"> <div class="promotion"> <div class="swiper-container"> <div class="swiper-wrapper"> <div class="swiper-slide"></div> </div> </div> <div class="swiper-pagination"></div> <div class="swiper-prev"></div> <div class="swiper-next"></div> </div> </section> - section 태그 자식요소로 div 를 만들고 자식요소로 스와이퍼 요소를 추가한다. 스와이퍼에서 제공하는 클래스이름은 변경하지 않고 그대로 사용한다. 스와이퍼의 부모요소인 section과 div 는 필요에 따라 변경해서 사용하면된다.
<section class="notice"> <div class="promotion"> <div class="swiper-container"> <div class="swiper-wrapper"> <div class="swiper-slide"></div> </div> </div> <div class="swiper-pagination"></div> <div class="swiper-prev"></div> <div class="swiper-next"></div> </div> </section> - 슬라이드에 추가할 이미지를img 태그를 이용해 swiper-slide 자식 요소로 입력한다.
<div class="swiper-slide"> <img src="./imgs/1.jpg" alt="" /> </div> <div class="swiper-slide"> <img src="./imgs/2.jpg" alt="" /> </div> <div class="swiper-slide"> <img src="./imgs/3.jpg" alt="" /> </div> <div class="swiper-slide"> <img src="./imgs/4.jpg" alt="" /> </div> <div class="swiper-slide"> <img src="./imgs/5.jpg" alt="" /> </div> <div class="swiper-slide"> <img src="./imgs/6.jpg" alt="" /> </div> <div class="swiper-slide"> <img src="./imgs/7.jpg" alt="" /> </div> <div class="swiper-slide"> <img src="./imgs/8.jpg" alt="" /> </div> - 구글 머티리얼 아이콘을 이용해 좌/우 화살표를 입력한다.
<div class="swiper-prev"> <span class="material-symbols-outlined"> chevron_left </span> </div> <div class="swiper-next"> <span class="material-symbols-outlined"> chevron_right </span> </div>
- section 태그 자식요소로 div 를 만들고 자식요소로 스와이퍼 요소를 추가한다. 스와이퍼에서 제공하는 클래스이름은 변경하지 않고 그대로 사용한다. 스와이퍼의 부모요소인 section과 div 는 필요에 따라 변경해서 사용하면된다.
7.2. STEP2
이미지 위치조정
- 슬라이드를 3장씩 보여주고 선택된 이미지는 중앙에 선명하게 보여 주고 양쪽에 이미지는 투명도를 0.4정도를 줘서 반투명하게 보여주 도록 한다. 세장의 이미지를 보여주기 위해 "swiper-container"의 폭을 3배 로 지정하고 간격을 20픽셀 더한 2,480픽셀로 지정한다.
.notice .promotion .swiper-container {
width: calc(420px * 3 + 20px);
height: 540px;
position: absolute;
top: 40px;
left: 50%;
transform: translateX(-50%);
}
7.3. STEP3
투명도 조정 및 버튼 배치
- 슬라이드에서 가운데 보여지는 이미지의 투명도를 1로 하고 양쪽에 이미지는 투명도를 0.4로 지정한다. 페이지네이션 블릿은 이미지("./imgs/promotion_slide_pager.png")를 백그라운로 지정한다. 그후 액티브 상태의 이미지 ("./imgs/promotion_slide_pager_on.png")를 교체하도록 설정한다.
.notice .promotion .swiper-slide { opacity: 0.4; transition: opacity 1s; position: relative; text-align: center; } .notice .promotion .swiper-slide img { width: 100%; height: 100%; /* 비율깨짐 */ object-fit: fill; object-fit: contain; object-fit: scale-down; object-fit: cover; /* 가로기준으로 비율에 맞게 채움 */ } .notice .promotion .swiper-slide-active { opacity: 1; } .notice .promotion .swiper-pagination { bottom: 40px; left: 0; right: 0; position: absolute; z-index: 9999; } .notice .promotion .swiper-pagination .swiper-pagination-bullet { background-color: transparent; background: url('./imgs/promotion_slide_pager.png') no-repeat center center/100%; width: 20px; height: 20px; margin-right: 6px; outline: none; } .notice .promotion .swiper-pagination .swiper-pagination-bullet:last-child { margin-right: 0; } .notice .promotion .swiper-pagination .swiper-pagination-bullet-active { background: url('./imgs/promotion_slide_pager_on.png') no-repeat center center/100%; }- 좌우로 이동하는 화살표에 호버를 설정한다.
.notice .promotion .swiper-prev, .notice .promotion .swiper-next { width: 42px; height: 42px; border: 2px solid rgb(255, 255, 255); border-radius: 50%; color: white; position: absolute; top: 300px; z-index: 1; cursor: pointer; outline: none; display: flex; justify-content: center; align-items: center; transition: 0.4s; user-select: none; } .notice .promotion .swiper-prev { left: 50%; margin-left: -480px; } .notice .promotion .swiper-next { right: 50%; margin-right: -480px; } .notice .promotion .swiper-prev:hover, .notice .promotion swiper-next:hover { background-color: rgb(255, 255, 255); color: rgb(0, 0, 0); }
- 좌우로 이동하는 화살표에 호버를 설정한다.
8. 동영상 슬라이더
<div class="swiper video-slider">
<div class="swiper-wrapper">
<div class="swiper-slide">
<video controls loop muted autoplay>
<source src="imgs/1.mp4" type="video/mp4" />
</video>
</div>
<div class="swiper-slide">
<video controls loop muted autoplay>
<source src="imgs/2.mp4" type="video/mp4" />
</video>
</div>
<div class="swiper-slide">
<video controls loop muted autoplay>
<source src="imgs/3.mp4" type="video/mp4" />
</video>
</div>
</div>
<div class="swiper-button-prev"></div>
<div class="swiper-button-next"></div>
</div>
9. 수직 슬라이더
<div class="swiper vertical">
<div class="swiper-wrapper">
<div class="swiper-slide">1</div>
<div class="swiper-slide">2</div>
<div class="swiper-slide">3</div>
</div>
<div class="swiper-pagination"></div>
</div>
<style>
.vertical { width: 100%; height: 100vh; }
</style>
<script>
const vertical = new Swiper('.vertical', {
direction: 'vertical', // 수직 방향
slidesPerView: 1,
mousewheel: true, // 마우스 휠로 이동
pagination: {
el: '.swiper-pagination',
clickable: true
}
});
</script>
10. 페이지네이션 종류
10.1. 기본 (bullets)
pagination: {
el: '.swiper-pagination',
clickable: true
}
10.2. 숫자형
pagination: {
el: '.swiper-pagination',
clickable: true,
renderBullet: function(index, className) {
return '<span class="' + className + '">' + (index + 1) + '</span>';
}
}
10.3. 프로그래스바
pagination: {
el: '.swiper-pagination',
type: 'progressbar'
}
10.4. 분수형
pagination: {
el: '.swiper-pagination',
type: 'fraction'
}
11. 이벤트 활용
const swiper = new Swiper('.swiper', {
on: {
// 초기화 완료
init: function() {
console.log('Swiper 초기화 완료');
},
// 슬라이드 변경
slideChange: function() {
console.log('현재 슬라이드:', this.realIndex);
},
// 슬라이드 변경 완료
slideChangeTransitionEnd: function() {
console.log('전환 완료');
}
}
});