알림
알림 (Alerts)
일반적인 사용자 동작에 대한 맥락적 피드백 메시지를 유연한 알림 메시지들로 제공합니다.
출처: 문서
본문
예제 (Examples)
알림은 어떤 길이의 텍스트에도 사용할 수 있고, 선택적으로 닫기 버튼도 제공합니다. 올바른 스타일링을 위해 여덟 가지 필수 맥락 클래스(예: .alert-success) 중 하나를 사용하세요. 인라인으로 닫기(dismiss)하려면 알림 JavaScript 플러그인을 사용하세요.
주의! v5.3.0부터 alert-variant() Sass 믹스인은 폐기(더 이상 사용하지 않음)되었습니다. 알림 변형은 이제 Sass 루프에서 CSS 변수를 덮어쓰는 방식으로 처리됩니다.
<div class="alert alert-primary" role="alert">
A simple primary alert—check it out!
</div>
<div class="alert alert-secondary" role="alert">
A simple secondary alert—check it out!
</div>
<div class="alert alert-success" role="alert">
A simple success alert—check it out!
</div>
<div class="alert alert-danger" role="alert">
A simple danger alert—check it out!
</div>
<div class="alert alert-warning" role="alert">
A simple warning alert—check it out!
</div>
<div class="alert alert-info" role="alert">
A simple info alert—check it out!
</div>
<div class="alert alert-light" role="alert">
A simple light alert—check it out!
</div>
<div class="alert alert-dark" role="alert">
A simple dark alert—check it out!
</div>
접근성 팁: 의미를 전달하기 위해 색만 사용하는 것은 시각적 표시일 뿐, 스크린 리더 같은 보조 기술 사용자에게는 전달되지 않습니다. 의미가 콘텐츠 자체에서 분명하거나(예: 충분한 색 대비를 가진 보이는 텍스트), .visually-hidden 클래스로 숨긴 추가 텍스트 같은 대체 수단으로 포함되는지 확인하세요.
라이브 예제 (Live example)
아래 버튼을 클릭하면 알림을 보여주고(처음에는 인라인 스타일로 숨겨져 있습니다), 내장된 닫기 버튼으로 닫고(제거하고) 다룰 수 있습니다.
<div id="liveAlertPlaceholder"></div>
<button type="button" class="btn btn-primary" id="liveAlertBtn">Show live alert</button>
라이브 알림 데모를 트리거하기 위해 다음 JavaScript를 사용합니다.
const alertPlaceholder = document.getElementById('liveAlertPlaceholder')
const appendAlert = (message, type) => {
const wrapper = document.createElement('div')
wrapper.innerHTML = [
`<div class="alert alert-${type} alert-dismissible" role="alert">`,
` <div>${message}</div>`,
' <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>',
'</div>'
].join('')
alertPlaceholder.append(wrapper)
}
const alertTrigger = document.getElementById('liveAlertBtn')
if (alertTrigger) {
alertTrigger.addEventListener('click', () => {
appendAlert('Nice, you triggered this alert message!', 'success')
})
}
링크 색 (Link color)
.alert-link 유틸리티 클래스를 사용하면 어떤 알림 안에서도 색이 어울리는 링크를 빠르게 제공할 수 있습니다.
<div class="alert alert-primary" role="alert">
A simple primary alert with <a href="#" class="alert-link">an example link</a>. Give it a click if you like.
</div>
<div class="alert alert-secondary" role="alert">
A simple secondary alert with <a href="#" class="alert-link">an example link</a>. Give it a click if you like.
</div>
<div class="alert alert-success" role="alert">
A simple success alert with <a href="#" class="alert-link">an example link</a>. Give it a click if you like.
</div>
<div class="alert alert-danger" role="alert">
A simple danger alert with <a href="#" class="alert-link">an example link</a>. Give it a click if you like.
</div>
<div class="alert alert-warning" role="alert">
A simple warning alert with <a href="#" class="alert-link">an example link</a>. Give it a click if you like.
</div>
<div class="alert alert-info" role="alert">
A simple info alert with <a href="#" class="alert-link">an example link</a>. Give it a click if you like.
</div>
<div class="alert alert-light" role="alert">
A simple light alert with <a href="#" class="alert-link">an example link</a>. Give it a click if you like.
</div>
<div class="alert alert-dark" role="alert">
A simple dark alert with <a href="#" class="alert-link">an example link</a>. Give it a click if you like.
</div>
추가 콘텐츠 (Additional content)
알림에는 제목, 문단, 구분선 같은 추가 HTML 요소도 포함할 수 있습니다.
<div class="alert alert-success" role="alert">
<h4 class="alert-heading">Well done!</h4>
<p>Aww yeah, you successfully read this important alert message. This example text is going to run a bit longer so that you can see how spacing within an alert works with this kind of content.</p>
<hr>
<p class="mb-0">Whenever you need to, be sure to use margin utilities to keep things nice and tidy.</p>
</div>
아이콘 (Icons)
마찬가지로 flexbox 유틸리티와 Bootstrap Icons를 사용해 아이콘이 있는 알림을 만들 수 있습니다. 아이콘과 콘텐츠에 따라 유틸리티나 커스텀 스타일을 추가하고 싶을 수 있습니다.
<div class="alert alert-primary d-flex align-items-center" role="alert">
<svg xmlns="http://www.w3.org/2000/svg" class="bi flex-shrink-0 me-2" viewBox="0 0 16 16" role="img" aria-label="Warning:">
<path d="M8.982 1.566a1.13 1.13 0 0 0-1.96 0L.165 13.233c-.457.778.091 1.767.98 1.767h13.713c.889 0 1.438-.99.98-1.767L8.982 1.566zM8 5c.535 0 .954.462.9.995l-.35 3.507a.552.552 0 0 1-1.1 0L7.1 5.995A.905.905 0 0 1 8 5zm.002 6a1 1 0 1 1 0 2 1 1 0 0 1 0-2z"/>
</svg>
<div>
An example alert with an icon
</div>
</div>
알림에 아이콘이 하나 이상 필요하신가요? Bootstrap Icons를 더 사용하고, 아래처럼 로컬 SVG 스프라이트를 만들어 같은 아이콘을 반복해서 쉽게 참조해 보세요.
<svg xmlns="http://www.w3.org/2000/svg" class="d-none">
<symbol id="check-circle-fill" viewBox="0 0 16 16">
<path d="M16 8A8 8 0 1 1 0 8a8 8 0 0 1 16 0zm-3.97-3.03a.75.75 0 0 0-1.08.022L7.477 9.417 5.384 7.323a.75.75 0 0 0-1.06 1.06L6.97 11.03a.75.75 0 0 0 1.079-.02l3.992-4.99a.75.75 0 0 0-.01-1.05z"/>
</symbol>
<symbol id="info-fill" viewBox="0 0 16 16">
<path d="M8 16A8 8 0 1 0 8 0a8 8 0 0 0 0 16zm.93-9.412-1 4.705c-.07.34.029.533.304.533.194 0 .487-.07.686-.246l-.088.416c-.287.346-.92.598-1.465.598-.703 0-1.002-.422-.808-1.319l.738-3.468c.064-.293.006-.399-.287-.47l-.451-.081.082-.381 2.29-.287zM8 5.5a1 1 0 1 1 0-2 1 1 0 0 1 0 2z"/>
</symbol>
<symbol id="exclamation-triangle-fill" viewBox="0 0 16 16">
<path d="M8.982 1.566a1.13 1.13 0 0 0-1.96 0L.165 13.233c-.457.778.091 1.767.98 1.767h13.713c.889 0 1.438-.99.98-1.767L8.982 1.566zM8 5c.535 0 .954.462.9.995l-.35 3.507a.552.552 0 0 1-1.1 0L7.1 5.995A.905.905 0 0 1 8 5zm.002 6a1 1 0 1 1 0 2 1 1 0 0 1 0-2z"/>
</symbol>
</svg>
<div class="alert alert-primary d-flex align-items-center" role="alert">
<svg class="bi flex-shrink-0 me-2" role="img" aria-label="Info:"><use xlink:href="#info-fill"/></svg>
<div>
An example alert with an icon
</div>
</div>
<div class="alert alert-success d-flex align-items-center" role="alert">
<svg class="bi flex-shrink-0 me-2" role="img" aria-label="Success:"><use xlink:href="#check-circle-fill"/></svg>
<div>
An example success alert with an icon
</div>
</div>
<div class="alert alert-warning d-flex align-items-center" role="alert">
<svg class="bi flex-shrink-0 me-2" role="img" aria-label="Warning:"><use xlink:href="#exclamation-triangle-fill"/></svg>
<div>
An example warning alert with an icon
</div>
</div>
<div class="alert alert-danger d-flex align-items-center" role="alert">
<svg class="bi flex-shrink-0 me-2" role="img" aria-label="Danger:"><use xlink:href="#exclamation-triangle-fill"/></svg>
<div>
An example danger alert with an icon
</div>
</div>
닫기 (Dismissing)
알림 JavaScript 플러그인을 사용하면 어떤 알림이라도 인라인으로 닫을 수 있습니다. 방법은 다음과 같습니다.
- 알림 플러그인 또는 컴파일된 Bootstrap JavaScript를 로드했는지 확인하세요.
- 닫기 버튼과
.alert-dismissible클래스를 추가하세요. 이 클래스는 알림 오른쪽에 추가 패딩을 주고 닫기 버튼을 배치합니다. - 닫기 버튼에
data-bs-dismiss="alert"속성을 추가하면 JavaScript 기능이 트리거됩니다. 모든 기기에서 올바른 동작을 위해<button>요소와 함께 사용하세요. - 알림을 닫을 때 애니메이션하려면
.fade와.show클래스를 추가하세요.
라이브 데모로 직접 확인할 수 있습니다:
<div class="alert alert-warning alert-dismissible fade show" role="alert">
<strong>Holy guacamole!</strong> You should check in on some of those fields below.
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
알림이 닫히면 요소는 페이지 구조에서 완전히 제거됩니다. 키보드 사용자가 닫기 버튼으로 알림을 닫으면 포커스가 갑자기 사라지고, 브라우저에 따라 페이지/문서의 시작 부분으로 재설정될 수 있습니다. 이런 이유로 closed.bs.alert 이벤트를 듣고 페이지에서 가장 적절한 위치로 프로그래밍 방식으로 focus()를 설정하는 추가 JavaScript를 포함할 것을 권장합니다. 보통은 포커스를 받지 않는 비-대화형 요소로 포커스를 옮길 계획이라면, 해당 요소에 tabindex="-1"을 추가하세요.
CSS
변수 (Variables) — v5.2.0에서 추가
Bootstrap의 진화하는 CSS 변수 접근 방식에 따라, 알림은 이제 .alert에 로컬 CSS 변수를 사용해 실시간 커스터마이징을 강화합니다. CSS 변수의 값은 Sass를 통해 설정되므로 Sass 커스터마이징도 여전히 지원됩니다.
--#{$prefix}alert-bg: transparent;
--#{$prefix}alert-padding-x: #{$alert-padding-x};
--#{$prefix}alert-padding-y: #{$alert-padding-y};
--#{$prefix}alert-margin-bottom: #{$alert-margin-bottom};
--#{$prefix}alert-color: inherit;
--#{$prefix}alert-border-color: transparent;
--#{$prefix}alert-border: #{$alert-border-width} solid var(--#{$prefix}alert-border-color);
--#{$prefix}alert-border-radius: #{$alert-border-radius};
--#{$prefix}alert-link-color: inherit;
Sass 변수 (Sass variables)
$alert-padding-y: $spacer;
$alert-padding-x: $spacer;
$alert-margin-bottom: 1rem;
$alert-border-radius: var(--#{$prefix}border-radius);
$alert-link-font-weight: $font-weight-bold;
$alert-border-width: var(--#{$prefix}border-width);
$alert-dismissible-padding-r: $alert-padding-x * 3; // 3x covers width of x plus default padding on either side
Sass 믹스인 (Sass mixins) — v5.3.0에서 폐기
@mixin alert-variant($background, $border, $color) {
--#{$prefix}alert-color: #{$color};
--#{$prefix}alert-bg: #{$background};
--#{$prefix}alert-border-color: #{$border};
--#{$prefix}alert-link-color: #{shade-color($color, 20%)};
@if $enable-gradients {
background-image: var(--#{$prefix}gradient);
}
.alert-link {
color: var(--#{$prefix}alert-link-color);
}
}
Sass 루프 (Sass loops)
CSS 변수를 덮어쓰며 변형(modifier) 클래스를 생성하는 루프입니다.
// Generate contextual modifier classes for colorizing the alert
@each $state in map-keys($theme-colors) {
.alert-#{$state} {
--#{$prefix}alert-color: var(--#{$prefix}#{$state}-text-emphasis);
--#{$prefix}alert-bg: var(--#{$prefix}#{$state}-bg-subtle);
--#{$prefix}alert-border-color: var(--#{$prefix}#{$state}-border-subtle);
--#{$prefix}alert-link-color: var(--#{$prefix}#{$state}-text-emphasis);
}
}
JavaScript 동작 (JavaScript behavior)
초기화 (Initialize)
요소를 알림으로 초기화합니다.
const alertList = document.querySelectorAll('.alert')
const alerts = [...alertList].map(element => new bootstrap.Alert(element))
알림을 닫는 것만이 목적이라면 JS API로 컴포넌트를 수동으로 초기화할 필요는 없습니다. data-bs-dismiss="alert"를 사용하면 컴포넌트가 자동으로 초기화되고 제대로 닫히게 됩니다. 자세한 내용은 트리거 섹션을 참고하세요.
트리거 (Triggers)
아래처럼 알림 내부의 버튼에 data-bs-dismiss 속성을 사용해 닫기를 수행할 수 있습니다.
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
또는 아래처럼 추가 data-bs-target을 사용해 알림 바깥의 버튼에서 수행할 수 있습니다.
<button type="button" class="btn-close" data-bs-dismiss="alert" data-bs-target="#my-alert" aria-label="Close"></button>
알림을 닫으면 DOM에서 제거된다는 점을 유의하세요.
메서드 (Methods)
alert 생성자로 알림 인스턴스를 만들 수 있습니다:
const bsAlert = new bootstrap.Alert('#myAlert')
이렇게 하면 알림이 data-bs-dismiss="alert" 속성을 가진 하위 요소들의 클릭 이벤트를 듣게 됩니다. (data-api의 자동 초기화를 사용할 때는 필요하지 않습니다.)
| 메서드 | 설명 |
|---|---|
| close | 알림을 DOM에서 제거해 닫습니다. 요소에 .fade와 .show 클래스가 있으면 제거되기 전에 페이드아웃됩니다. |
| dispose | 요소의 알림을 파괴합니다. (DOM 요소에 저장된 데이터를 제거합니다.) |
| getInstance | DOM 요소에 연결된 알림 인스턴스를 가져올 수 있는 정적 메서드입니다. 예: bootstrap.Alert.getInstance(alert). |
| getOrCreateInstance | DOM 요소에 연결된 알림 인스턴스를 반환하거나, 초기화되지 않았다면 새로 만드는 정적 메서드입니다. 이렇게 사용할 수 있습니다: bootstrap.Alert.getOrCreateInstance(element). |
기본 사용법:
const alert = bootstrap.Alert.getOrCreateInstance('#myAlert')
alert.close()
이벤트 (Events)
Bootstrap의 알림 플러그인은 알림 기능에 훅을 걸기 위한 몇 가지 이벤트를 노출합니다.
| 이벤트 | 설명 |
|---|---|
| close.bs.alert | close 인스턴스 메서드가 호출되는 즉시 발생합니다. |
| closed.bs.alert | 알림이 닫히고 CSS 전환이 완료되었을 때 발생합니다. |
const myAlert = document.getElementById('myAlert')
myAlert.addEventListener('closed.bs.alert', event => {
// do something, for instance, explicitly move focus to the most appropriate element,
// so it doesn’t get lost/reset to the start of the page
// document.getElementById('...').focus()
})