Tooltips
Tooltips (툴팁)
CSS3 애니메이션과 로컬 타이틀 저장을 위한 data-bs-속성(data-bs-attributes)을 사용해 CSS와 JavaScript로 커스텀 Bootstrap 툴팁을 추가하는 문서와 예시를 다룹니다.
출처: 문서
본문
개요 (Overview)
tooltip 플러그인을 사용할 때 알아둘 것들:
- 툴팁은 위치 지정을 위해 서드파티 라이브러리인 Popper에 의존합니다.
bootstrap.js보다 먼저popper.min.js를 포함하거나, Popper가 포함된bootstrap.bundle.min.js하나를 사용해야 합니다. - 성능상의 이유로 툴팁은 opt-in 방식이므로 직접 초기화해야 합니다.
- 제로 길이 타이틀을 가진 툴팁은 절대 표시되지 않습니다.
- 더 복잡한 컴포넌트(입력 그룹, 버튼 그룹 등)에서 렌더링 문제를 피하려면
container: 'body'를 지정하세요. - 숨겨진 요소에서 툴팁을 트리거하는 것은 동작하지 않습니다.
.disabled또는disabled요소의 툴팁은 래퍼 요소에서 트리거해야 합니다.- 여러 줄에 걸친 하이퍼링크에서 트리거할 때 툴팁은 가운데 정렬됩니다. 이 동작을 피하려면
<a>에white-space: nowrap;을 사용하세요. - 해당 요소들이 DOM에서 제거되기 전에 툴팁을 숨겨야 합니다.
- shadow DOM 안의 요소 덕분에 툴팁을 트리거할 수 있습니다.
다 이해했나요? 좋습니다. 몇 가지 예시로 어떻게 동작하는지 살펴보죠.
기본적으로 이 컴포넌트는 내장 콘텐츠 살균기(sanitizer)를 사용하며, 명시적으로 허용되지 않은 HTML 요소는 모두 제거합니다. 자세한 내용은 JavaScript 문서의 sanitizer 섹션을 참고하세요.
이 컴포넌트의 애니메이션 효과는
prefers-reduced-motion미디어 쿼리에 의존합니다. 접근성 문서의 reduced motion 섹션을 참고하세요.
예시 (Examples)
툴팁 활성화 (Enable tooltips)
위에서 언급했듯이, 툴팁을 사용하려면 먼저 초기화해야 합니다. 페이지의 모든 툴팁을 초기화하는 한 가지 방법은 다음과 같이 data-bs-toggle 속성으로 선택하는 것입니다:
const tooltipTriggerList = document.querySelectorAll('[data-bs-toggle="tooltip"]')
const tooltipList = [...tooltipTriggerList].map(tooltipTriggerEl => new bootstrap.Tooltip(tooltipTriggerEl))
링크에 툴팁 (Tooltips on links)
아래 링크에 마우스를 올리면 툴팁을 볼 수 있습니다:
<p class="muted">Placeholder text to demonstrate some <a href="#" data-bs-toggle="tooltip" data-bs-title="Default tooltip">inline links</a> with tooltips. This is now just filler, no killer. Content placed here just to mimic the presence of <a href="#" data-bs-toggle="tooltip" data-bs-title="Another tooltip">real text</a>. And all that just to give you an idea of how tooltips would look when used in real-world situations. So hopefully you’ve now seen how <a href="#" data-bs-toggle="tooltip" data-bs-title="Another one here too">these tooltips on links</a> can work in practice, once you use them on <a href="#" data-bs-toggle="tooltip" data-bs-title="The last tip!">your own</a> site or project.</p>
HTML에서 title이나 data-bs-title 중 원하는 것을 사용해도 됩니다. title을 사용하면 Popper가 요소가 렌더링될 때 자동으로 data-bs-title로 교체합니다.
커스텀 툴팁 (Custom tooltips)
v5.2.0에서 추가됨
CSS 변수를 사용해 툴팁의 모양을 커스터마이즈할 수 있습니다. 커스텀 모양을 범위 지정하기 위해 data-bs-custom-class="custom-tooltip"으로 커스텀 클래스를 설정하고, 그 클래스로 로컬 CSS 변수를 덮어쓰는 데 사용합니다.
.custom-tooltip {
--bs-tooltip-bg: var(--bd-violet-bg);
--bs-tooltip-color: var(--bs-white);
}
<button type="button" class="btn btn-secondary"
data-bs-toggle="tooltip" data-bs-placement="top"
data-bs-custom-class="custom-tooltip"
data-bs-title="This top tooltip is themed via CSS variables.">
Custom tooltip
</button>
방향 (Directions)
아래 버튼들에 마우스를 올리면 네 가지 툴팁 방향을 볼 수 있습니다: top, right, bottom, left. Bootstrap을 RTL로 사용할 때는 방향이 반전됩니다.
<button type="button" class="btn btn-secondary" data-bs-toggle="tooltip" data-bs-placement="top" data-bs-title="Tooltip on top">
Tooltip on top
</button>
<button type="button" class="btn btn-secondary" data-bs-toggle="tooltip" data-bs-placement="right" data-bs-title="Tooltip on right">
Tooltip on right
</button>
<button type="button" class="btn btn-secondary" data-bs-toggle="tooltip" data-bs-placement="bottom" data-bs-title="Tooltip on bottom">
Tooltip on bottom
</button>
<button type="button" class="btn btn-secondary" data-bs-toggle="tooltip" data-bs-placement="left" data-bs-title="Tooltip on left">
Tooltip on left
</button>
커스텀 HTML을 추가한 경우:
<button type="button" class="btn btn-secondary" data-bs-toggle="tooltip" data-bs-html="true" data-bs-title="<em>Tooltip</em> <u>with</u> <b>HTML</b>">
Tooltip with HTML
</button>
SVG와 함께:
CSS
변수 (Variables)
v5.2.0에서 추가됨
Bootstrap의 진화하는 CSS 변수 접근 방식의 일부로, 툴팁은 이제 향상된 실시간 커스터마이즈를 위해 .tooltip에 로컬 CSS 변수를 사용합니다. CSS 변수의 값은 Sass로 설정되므로 Sass 커스터마이즈도 여전히 지원됩니다.
--#{$prefix}tooltip-zindex: #{$zindex-tooltip};
--#{$prefix}tooltip-max-width: #{$tooltip-max-width};
--#{$prefix}tooltip-padding-x: #{$tooltip-padding-x};
--#{$prefix}tooltip-padding-y: #{$tooltip-padding-y};
--#{$prefix}tooltip-margin: #{$tooltip-margin};
@include rfs($tooltip-font-size, --#{$prefix}tooltip-font-size);
--#{$prefix}tooltip-color: #{$tooltip-color};
--#{$prefix}tooltip-bg: #{$tooltip-bg};
--#{$prefix}tooltip-border-radius: #{$tooltip-border-radius};
--#{$prefix}tooltip-opacity: #{$tooltip-opacity};
--#{$prefix}tooltip-arrow-width: #{$tooltip-arrow-width};
--#{$prefix}tooltip-arrow-height: #{$tooltip-arrow-height};
Sass 변수
$tooltip-font-size: $font-size-sm;
$tooltip-max-width: 200px;
$tooltip-color: var(--#{$prefix}body-bg);
$tooltip-bg: var(--#{$prefix}emphasis-color);
$tooltip-border-radius: var(--#{$prefix}border-radius);
$tooltip-opacity: .9;
$tooltip-padding-y: $spacer * .25;
$tooltip-padding-x: $spacer * .5;
$tooltip-margin: null; // TODO: remove this in v6
$tooltip-arrow-width: .8rem;
$tooltip-arrow-height: .4rem;
// fusv-disable
$tooltip-arrow-color: null; // Deprecated in Bootstrap 5.2.0 for CSS variables
// fusv-enable
사용법 (Usage)
tooltip 플러그인은 콘텐츠와 마크업을 필요할 때(on demand) 생성하며, 기본적으로 트리거 요소 뒤에 툴팁을 배치합니다. JavaScript로 툴팁을 트리거하세요:
const exampleEl = document.getElementById('example')
const tooltip = new bootstrap.Tooltip(exampleEl, options)
부모 컨테이너에 overflow: auto나 overflow: scroll이 있으면 툴팁은 자동으로 위치를 바꾸려 시도하지만, 원래 배치의 위치 지정은 유지합니다. boundary 옵션(popperConfig 옵션을 통한 flip modifier용)을 'clippingParents' 기본값 대신 document.body 같은 임의의 HTMLElement로 설정해 덮어쓸 수 있습니다:
const tooltip = new bootstrap.Tooltip('#example', {
boundary: document.body // or document.querySelector('#boundary')
})
마크업 (Markup)
툴팁에 필요한 마크업은 툴팁을 붙이고 싶은 HTML 요소의 data 속성과 title뿐입니다. 생성된 툴팁의 마크업은 꽤 단순하지만, 위치가 필요합니다(기본적으로 플러그인이 top으로 설정).
툴팁은 전통적으로 키보드 포커스가 가능하고 상호작용적인 HTML 요소(링크나 폼 컨트롤 등)에만 추가해서 키보드 및 보조 기술 사용자에게 접근 가능하게 유지하세요. 다른 HTML 요소도 tabindex="0"을 추가해 포커스 가능하게 만들 수 있지만, 이렇게 하면 비상호작용 요소에 키보드 사용자에게 성가시고 혼란스러운 탭 정지(tab stop)가 생길 수 있고, 대부분의 보조 기술은 이런 상황에서 툴팁을 알려주지 않습니다. 또한 툴팁 트리거를 hover에만 의존하지 마세요. 그러면 키보드 사용자가 트리거할 수 없게 됩니다.
<!-- HTML to write -->
<a href="#" data-bs-toggle="tooltip" data-bs-title="Some tooltip text!">Hover over me</a>
<!-- Generated markup by the plugin -->
<div class="tooltip bs-tooltip-auto" role="tooltip">
<div class="tooltip-arrow"></div>
<div class="tooltip-inner">
Some tooltip text!
</div>
</div>
비활성 요소 (Disabled elements)
disabled 속성이 있는 요소는 상호작용적이지 않으므로, 사용자가 포커스하거나 호버하거나 클릭해서 툴팁(또는 팝오버)을 트리거할 수 없습니다. 해결 방법으로 래퍼 <div>나 <span>에서 툴팁을 트리거하되, 이상적으로는 tabindex="0"으로 키보드 포커스가 가능하게 만드세요.
<span class="d-inline-block" tabindex="0" data-bs-toggle="tooltip" data-bs-title="Disabled tooltip">
<button class="btn btn-primary" type="button" disabled>Disabled button</button>
</span>
옵션 (Options)
옵션은 data 속성이나 JavaScript로 전달할 수 있으므로, data-bs-animation="{value}"처럼 data-bs-에 옵션 이름을 붙일 수 있습니다. data 속성으로 옵션을 전달할 때는 옵션 이름의 대소문자 형태를 "camelCase"에서 "kebab-case"로 바꿔야 합니다. 예를 들어 data-bs-customClass="beautifier" 대신 data-bs-custom-class="beautifier"를 사용하세요.
Bootstrap 5.2.0부터 모든 컴포넌트는 JSON 문자열로 간단한 컴포넌트 설정을 담을 수 있는 실험적인 예약 data 속성 data-bs-config를 지원합니다. 요소에 data-bs-config='{"delay":0, "title":123}'과 data-bs-title="456" 속성이 있으면 최종 title 값은 456이 되고, 별도의 data 속성이 data-bs-config에 주어진 값을 덮어씁니다. 또한 기존 data 속성도 data-bs-delay='{"show":0,"hide":150}'처럼 JSON 값을 담을 수 있습니다.
최종 설정 객체는 data-bs-config, data-bs-, js object를 병합한 결과이며, 가장 마지막에 주어진 키-값이 나머지를 덮어씁니다.
보안상의 이유로
sanitize,sanitizeFn,allowList옵션은 data 속성으로 제공할 수 없습니다.
| 이름 | 타입 | 기본값 | 설명 |
|---|---|---|---|
allowList |
object | 기본값 | 허용된 태그와 속성을 담고 있는 객체입니다. 명시적으로 허용되지 않은 것은 콘텐츠 살균기가 제거합니다. 이 목록에 추가할 때는 주의하세요. 자세한 내용은 OWASP의 Cross Site Scripting Prevention Cheat Sheet를 참고하세요. |
animation |
boolean | true |
툴팁에 CSS fade 전환을 적용합니다. |
boundary |
string, element | 'clippingParents' |
툴팁의 overflow 제약 경계입니다(Popper의 preventOverflow modifier에만 적용). 기본값은 'clippingParents'이며 HTMLElement 참조(JavaScript로만)를 받을 수 있습니다. 자세한 내용은 Popper의 detectOverflow 문서를 참고하세요. |
container |
string, element, false | false |
툴팁을 특정 요소에 추가합니다. 예: container: 'body'. 이 옵션은 트리거 요소 근처의 문서 흐름에 툴팁을 배치할 수 있게 해 주어 특히 유용합니다. 창 크기가 조정되는 동안 툴팁이 트리거 요소에서 떠내려가는 것을 막아 줍니다. |
customClass |
string, function | '' |
툴팁이 표시될 때 클래스를 추가합니다. 이 클래스들은 template에 지정된 어떤 클래스에 더해 추가됩니다. 여러 클래스를 추가하려면 공백으로 구분하세요: 'class-1 class-2'. 추가 클래스 이름을 담은 단일 문자열을 반환하는 함수를 전달할 수도 있습니다. |
delay |
number, object | 0 |
툴팁 표시/숨기기를 지연합니다(ms) — 수동(manual) 트리거 타입에는 적용되지 않습니다. 숫자가 주어지면 hide/show 양쪽에 지연이 적용됩니다. 객체 구조는 delay: { "show": 500, "hide": 100 }입니다. |
fallbackPlacements |
array | ['top', 'right', 'bottom', 'left'] |
배열에 배치 목록(우선순위 순서)을 제공해 대체 배치를 정의합니다. 자세한 내용은 Popper의 behavior 문서를 참고하세요. |
html |
boolean | false |
툴팁에서 HTML을 허용합니다. true면 툴팁의 title에 있는 HTML 태그가 툴팁에서 렌더링됩니다. false면 innerText 속성이 콘텐츠를 DOM에 삽입하는 데 사용됩니다. XSS 공격을 막으려면 사용자 생성 입력을 다룰 때는 텍스트를 선호하세요. |
offset |
array, string, function | [0, 6] |
툴팁의 대상에 대한 오프셋입니다. data 속성에서는 data-bs-offset="10,20"처럼 쉼표로 구분된 값을 가진 문자열을 전달할 수 있습니다. 함수로 오프셋을 결정할 때는 첫 번째 인자로 popper placement, reference, popper rects를 담은 객체와 함께 호출됩니다. 트리거 요소의 DOM 노드는 두 번째 인자로 전달됩니다. 함수는 skidding, distance의 두 숫자를 담은 배열을 반환해야 합니다. 자세한 내용은 Popper의 offset 문서를 참고하세요. |
placement |
string, function | 'top' |
툴팁 위치 지정 방법: auto, top, bottom, left, right. auto를 지정하면 툴팁을 동적으로 방향을 바꿉니다. 함수로 배치를 결정할 때는 첫 번째 인자로 툴팁 DOM 노드, 두 번째 인자로 트리거 요소 DOM 노드와 함께 호출됩니다. this 컨텍스트는 툴팁 인스턴스로 설정됩니다. |
popperConfig |
null, object, function | null |
Bootstrap의 기본 Popper 설정을 바꾸려면 Popper의 configuration을 참고하세요. Popper 설정을 만드는 데 함수를 사용하면 Bootstrap의 기본 Popper 설정을 담은 객체와 함께 호출됩니다. 기본값과 자신의 설정을 병합하고 사용하는 데 도움이 됩니다. 함수는 Popper용 설정 객체를 반환해야 합니다. |
sanitize |
boolean | true |
콘텐츠 살균을 활성화합니다. true면 template, content, title 옵션이 살균됩니다. 콘텐츠 살균을 비활성화할 때는 주의하세요. 자세한 내용은 OWASP의 Cross Site Scripting Prevention Cheat Sheet를 참고하세요. 콘텐츠 살균 비활성화만으로 인한 취약점은 Bootstrap의 보안 모델 범위에 포함되지 않습니다. |
sanitizeFn |
null, function | null |
대체 콘텐츠 살균 함수를 제공합니다. 살균을 수행하기 위해 전용 라이브러리를 선호한다면 유용합니다. |
selector |
string, false | false |
selector가 제공되면 툴팁 객체가 지정된 대상에 위임됩니다. 실제로는 동적으로 추가된 DOM 요소에도 툴팁을 적용하는 데 사용됩니다(jQuery.on 지원). 이 이슈와 유익한 예시를 참고하세요. 참고: title 속성은 selector로 사용하면 안 됩니다. |
template |
string | '<div class="tooltip" role="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>' |
툴팁을 만들 때 사용할 기본 HTML입니다. 툴팁의 title은 .tooltip-inner에 주입됩니다. .tooltip-arrow는 툴팁의 화살표가 됩니다. 가장 바깥 래퍼 요소에는 .tooltip 클래스와 role="tooltip"이 있어야 합니다. |
title |
string, element, function | '' |
툴팁 제목입니다. 함수가 주어지면 팝오버가 붙어 있는 요소로 this 참조가 설정된 채 호출됩니다. |
trigger |
string | 'hover focus' |
툴팁 트리거 방법: click, hover, focus, manual. 여러 트리거를 공백으로 구분해 전달할 수 있습니다. 'manual'은 툴팁이 .tooltip('show'), .tooltip('hide'), .tooltip('toggle') 메서드를 통해 프로그램 방식으로 트리거됨을 나타냅니다. 이 값은 다른 어떤 트리거와도 결합할 수 없습니다. 'hover' 단독은 키보드로 트리거할 수 없는 툴팁을 만들며, 키보드 사용자에게 동일한 정보를 전달하는 대체 방법이 있을 때만 사용해야 합니다. |
개별 툴팁의 data 속성 (Data attributes for individual tooltips)
개별 툴팁의 옵션은 위에서 설명한 대로 data 속성을 사용해 대체로 지정할 수 있습니다.
popperConfig와 함께 함수 사용 (Using function with popperConfig)
const tooltip = new bootstrap.Tooltip(element, {
popperConfig(defaultBsPopperConfig) {
// const newPopperConfig = {...}
// use defaultBsPopperConfig if needed...
// return newPopperConfig
}
})
메서드 (Methods)
모든 API 메서드는 비동기이며 전환을 시작합니다. 전환이 시작되는 즉시 호출자에게 반환되지만, 끝나기 전에 반환됩니다. 또한 전환 중인 컴포넌트에 대한 메서드 호출은 무시됩니다. JavaScript 문서에서 자세히 알아보세요.
| 메서드 | 설명 |
|---|---|
disable |
요소의 툴팁이 표시되는 능력을 제거합니다. 다시 활성화되어야만 툴팁이 표시될 수 있습니다. |
dispose |
요소의 툴팁을 숨기고 파괴합니다(DOM 요소에 저장된 데이터를 제거합니다). 위임(delegation)을 사용하는 툴팁(selector 옵션으로 생성)은 하위 트리거 요소에서 개별적으로 파괴할 수 없습니다. |
enable |
요소의 툴팁에 표시될 수 있는 능력을 부여합니다. 툴팁은 기본적으로 활성화되어 있습니다. |
getInstance |
DOM 요소와 연결된 툴팁 인스턴스를 가져올 수 있게 해 주는 정적 메서드입니다. |
getOrCreateInstance |
DOM 요소와 연결된 툴팁 인스턴스를 가져오거나, 초기화되지 않은 경우 새로 만드는 정적 메서드입니다. |
hide |
요소의 툴팁을 숨깁니다. 툴팁이 실제로 숨겨지기 전에(hidden.bs.tooltip 이벤트 전에) 호출자에게 반환합니다. 툴팁의 "수동(manual)" 트리거로 간주됩니다. |
setContent |
초기화 후 툴팁의 콘텐츠를 바꿀 수 있는 방법을 제공합니다. |
show |
요소의 툴팁을 표시합니다. 툴팁이 실제로 표시되기 전에(shown.bs.tooltip 이벤트 전에) 호출자에게 반환합니다. 툴팁의 "수동(manual)" 트리거로 간주됩니다. 제로 길이 타이틀을 가진 툴팁은 절대 표시되지 않습니다. |
toggle |
요소의 툴팁을 토글합니다. 툴팁이 실제로 표시되거나 숨겨지기 전에(shown.bs.tooltip 또는 hidden.bs.tooltip 이벤트 전에) 호출자에게 반환합니다. 툴팁의 "수동(manual)" 트리거로 간주됩니다. |
toggleEnabled |
요소의 툴팁이 표시되거나 숨겨질 수 있는 능력을 토글합니다. |
update |
요소의 툴팁 위치를 업데이트합니다. |
const tooltip = bootstrap.Tooltip.getInstance('#example') // Returns a Bootstrap tooltip instance
// setContent example
tooltip.setContent({ '.tooltip-inner': 'another title' })
setContent 메서드는 object 인자를 받는데, 각 속성-키는 툴팁 template 안의 유효한 string selector이고, 각 관련 속성-값은 string | element | function | null이 될 수 있습니다.
이벤트 (Events)
| 이벤트 | 설명 |
|---|---|
hide.bs.tooltip |
hide 인스턴스 메서드가 호출될 때 즉시 발생하는 이벤트입니다. |
hidden.bs.tooltip |
툴팁이 사용자에게 숨겨지는 것을 마쳤을 때 발생하는 이벤트입니다(CSS 전환이 완료될 때까지 기다립니다). |
inserted.bs.tooltip |
툴팁 template이 DOM에 추가된 후 show.bs.tooltip 이벤트 다음에 발생하는 이벤트입니다. |
show.bs.tooltip |
show 인스턴스 메서드가 호출될 때 즉시 발생하는 이벤트입니다. |
shown.bs.tooltip |
툴팁이 사용자에게 표시되었을 때 발생하는 이벤트입니다(CSS 전환이 완료될 때까지 기다립니다). |
const myTooltipEl = document.getElementById('myTooltip')
const tooltip = bootstrap.Tooltip.getOrCreateInstance(myTooltipEl)
myTooltipEl.addEventListener('hidden.bs.tooltip', () => {
// do something...
})
tooltip.hide()