Modal
Use o plug-in modal JavaScript do Bootstrap para adicionar diálogos ao seu site para lightboxes, notificações do usuário ou conteúdo totalmente personalizado.
Como funciona
Antes de começar com o componente modal do Bootstrap, certifique-se de ler o seguinte, pois nossas opções de menu foram alteradas recentemente.
- Os modais são construídos com HTML, CSS e JavaScript. Eles são posicionados sobre todo o resto no documento e removem a rolagem do
<body>
para que o conteúdo modal seja rolado. - Clicar no modal “backdrop” fechará automaticamente o modal.
- Bootstrap suporta apenas uma janela modal por vez. Os modais aninhados não são compatíveis, pois acreditamos que sejam experiências de usuário ruins.
- Os modais usam
position: fixed
, que às vezes pode ser um pouco particular sobre sua renderização. Sempre que possível, coloque seu HTML modal em uma posição de nível superior para evitar possíveis interferências de outros elementos. Você provavelmente terá problemas ao aninhar um.modal
dentro de outro elemento fixo. - Mais uma vez, devido a
position: fixed
, existem algumas ressalvas com o uso de modais em dispositivos móveis. Consulte nossos documentos de suporte do navegador para obter detalhes. - Devido à forma como o HTML5 define sua semântica, o
autofocus
atributo HTML não tem efeito nos modais do Bootstrap. Para obter o mesmo efeito, use algum JavaScript personalizado:
const myModal = document.getElementById('myModal')
const myInput = document.getElementById('myInput')
myModal.addEventListener('shown.bs.modal', () => {
myInput.focus()
})
prefers-reduced-motion
consulta de mídia. Consulte a
seção de movimento reduzido de nossa documentação de acessibilidade .
Continue lendo para demonstrações e diretrizes de uso.
Exemplos
Componentes modais
Abaixo está um exemplo modal estáticoposition
(significando que e display
foram substituídos). Estão incluídos o cabeçalho modal, o corpo modal (obrigatório para padding
) e o rodapé modal (opcional). Pedimos que você inclua cabeçalhos modais com ações de dispensa sempre que possível ou forneça outra ação de dispensa explícita.
<div class="modal" tabindex="-1">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Modal title</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<p>Modal body text goes here.</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
Demonstração ao vivo
Alterne uma demonstração modal de trabalho clicando no botão abaixo. Ele deslizará para baixo e desaparecerá do topo da página.
<!-- Button trigger modal -->
<button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#exampleModal">
Launch demo modal
</button>
<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
...
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
Pano de fundo estático
Quando o pano de fundo é definido como estático, o modal não será fechado ao clicar fora dele. Clique no botão abaixo para experimentar.
<!-- Button trigger modal -->
<button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#staticBackdrop">
Launch static backdrop modal
</button>
<!-- Modal -->
<div class="modal fade" id="staticBackdrop" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="staticBackdropLabel">Modal title</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
...
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Understood</button>
</div>
</div>
</div>
</div>
Rolagem de conteúdo longo
Quando os modais se tornam muito longos para a janela de visualização ou dispositivo do usuário, eles rolam independentemente da própria página. Experimente a demonstração abaixo para ver o que queremos dizer.
Você também pode criar um modal rolável que permite rolar o corpo do modal adicionando .modal-dialog-scrollable
a .modal-dialog
.
<!-- Scrollable modal -->
<div class="modal-dialog modal-dialog-scrollable">
...
</div>
Centralizado verticalmente
Adicione .modal-dialog-centered
a .modal-dialog
para centralizar verticalmente o modal.
<!-- Vertically centered modal -->
<div class="modal-dialog modal-dialog-centered">
...
</div>
<!-- Vertically centered scrollable modal -->
<div class="modal-dialog modal-dialog-centered modal-dialog-scrollable">
...
</div>
Dicas de ferramentas e popovers
Dicas de ferramentas e popovers podem ser colocados dentro de modais conforme necessário. Quando os modais são fechados, quaisquer dicas de ferramentas e popovers também são descartados automaticamente.
<div class="modal-body">
<h5>Popover in a modal</h5>
<p>This <a href="#" role="button" class="btn btn-secondary" data-bs-toggle="popover" title="Popover title" data-bs-content="Popover body content is set in this attribute.">button</a> triggers a popover on click.</p>
<hr>
<h5>Tooltips in a modal</h5>
<p><a href="#" data-bs-toggle="tooltip" title="Tooltip">This link</a> and <a href="#" data-bs-toggle="tooltip" title="Tooltip">that link</a> have tooltips on hover.</p>
</div>
Usando a grade
Utilize o sistema de grade do Bootstrap em um modal aninhando -se .container-fluid
no arquivo .modal-body
. Em seguida, use as classes normais do sistema de grade como faria em qualquer outro lugar.
<div class="modal-body">
<div class="container-fluid">
<div class="row">
<div class="col-md-4">.col-md-4</div>
<div class="col-md-4 ms-auto">.col-md-4 .ms-auto</div>
</div>
<div class="row">
<div class="col-md-3 ms-auto">.col-md-3 .ms-auto</div>
<div class="col-md-2 ms-auto">.col-md-2 .ms-auto</div>
</div>
<div class="row">
<div class="col-md-6 ms-auto">.col-md-6 .ms-auto</div>
</div>
<div class="row">
<div class="col-sm-9">
Level 1: .col-sm-9
<div class="row">
<div class="col-8 col-sm-6">
Level 2: .col-8 .col-sm-6
</div>
<div class="col-4 col-sm-6">
Level 2: .col-4 .col-sm-6
</div>
</div>
</div>
</div>
</div>
</div>
Conteúdo modal variável
Tem um monte de botões que acionam o mesmo modal com conteúdos ligeiramente diferentes? Use event.relatedTarget
e atributos HTMLdata-bs-*
para variar o conteúdo do modal dependendo de qual botão foi clicado.
Abaixo está uma demonstração ao vivo seguida por um exemplo de HTML e JavaScript. Para obter mais informações, leia os documentos de eventos modais para obter detalhes sobre relatedTarget
.
<button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#exampleModal" data-bs-whatever="@mdo">Open modal for @mdo</button>
<button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#exampleModal" data-bs-whatever="@fat">Open modal for @fat</button>
<button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#exampleModal" data-bs-whatever="@getbootstrap">Open modal for @getbootstrap</button>
<div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">New message</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<form>
<div class="mb-3">
<label for="recipient-name" class="col-form-label">Recipient:</label>
<input type="text" class="form-control" id="recipient-name">
</div>
<div class="mb-3">
<label for="message-text" class="col-form-label">Message:</label>
<textarea class="form-control" id="message-text"></textarea>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Send message</button>
</div>
</div>
</div>
</div>
const exampleModal = document.getElementById('exampleModal')
exampleModal.addEventListener('show.bs.modal', event => {
// Button that triggered the modal
const button = event.relatedTarget
// Extract info from data-bs-* attributes
const recipient = button.getAttribute('data-bs-whatever')
// If necessary, you could initiate an AJAX request here
// and then do the updating in a callback.
//
// Update the modal's content.
const modalTitle = exampleModal.querySelector('.modal-title')
const modalBodyInput = exampleModal.querySelector('.modal-body input')
modalTitle.textContent = `New message to ${recipient}`
modalBodyInput.value = recipient
})
Alternar entre modais
Alterne entre vários modais com um posicionamento inteligente dos atributos data-bs-target
e . data-bs-toggle
Por exemplo, você pode alternar um modal de redefinição de senha de dentro de um modal de login já aberto. Observe que vários modais não podem ser abertos ao mesmo tempo - esse método simplesmente alterna entre dois modais separados.
<div class="modal fade" id="exampleModalToggle" aria-hidden="true" aria-labelledby="exampleModalToggleLabel" tabindex="-1">
<div class="modal-dialog modal-dialog-centered">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalToggleLabel">Modal 1</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
Show a second modal and hide this one with the button below.
</div>
<div class="modal-footer">
<button class="btn btn-primary" data-bs-target="#exampleModalToggle2" data-bs-toggle="modal">Open second modal</button>
</div>
</div>
</div>
</div>
<div class="modal fade" id="exampleModalToggle2" aria-hidden="true" aria-labelledby="exampleModalToggleLabel2" tabindex="-1">
<div class="modal-dialog modal-dialog-centered">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalToggleLabel2">Modal 2</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
Hide this modal and show the first with the button below.
</div>
<div class="modal-footer">
<button class="btn btn-primary" data-bs-target="#exampleModalToggle" data-bs-toggle="modal">Back to first</button>
</div>
</div>
</div>
</div>
<a class="btn btn-primary" data-bs-toggle="modal" href="#exampleModalToggle" role="button">Open first modal</a>
Alterar animação
A $modal-fade-transform
variável determina o estado de transformação de .modal-dialog
antes da animação de fade-in modal, a $modal-show-transform
variável determina a transformação de .modal-dialog
no final da animação de fade-in modal.
Se você quiser, por exemplo, uma animação com zoom, você pode definir $modal-fade-transform: scale(.8)
.
Remover animação
Para modais que simplesmente aparecem em vez de aparecer gradualmente, remova a .fade
classe de sua marcação modal.
<div class="modal" tabindex="-1" aria-labelledby="..." aria-hidden="true">
...
</div>
Alturas dinâmicas
If the height of a modal changes while it is open, you should call myModal.handleUpdate()
to readjust the modal’s position in case a scrollbar appears.
Accessibility
Be sure to add aria-labelledby="..."
, referencing the modal title, to .modal
. Additionally, you may give a description of your modal dialog with aria-describedby
on .modal
. Note that you don’t need to add role="dialog"
since we already add it via JavaScript.
Embedding YouTube videos
Embedding YouTube videos in modals requires additional JavaScript not in Bootstrap to automatically stop playback and more. See this helpful Stack Overflow post for more information.
Optional sizes
Modals have three optional sizes, available via modifier classes to be placed on a .modal-dialog
. These sizes kick in at certain breakpoints to avoid horizontal scrollbars on narrower viewports.
Size | Class | Modal max-width |
---|---|---|
Small | .modal-sm |
300px |
Default | None | 500px |
Large | .modal-lg |
800px |
Extra large | .modal-xl |
1140px |
Our default modal without modifier class constitutes the “medium” size modal.
<div class="modal-dialog modal-xl">...</div>
<div class="modal-dialog modal-lg">...</div>
<div class="modal-dialog modal-sm">...</div>
Fullscreen Modal
Another override is the option to pop up a modal that covers the user viewport, available via modifier classes that are placed on a .modal-dialog
.
Class | Availability | |
---|---|---|
.modal-fullscreen |
Always | |
.modal-fullscreen-sm-down |
576px |
|
.modal-fullscreen-md-down |
768px |
|
.modal-fullscreen-lg-down |
992px |
|
.modal-fullscreen-xl-down |
1200px |
|
.modal-fullscreen-xxl-down |
1400px |
<!-- Full screen modal -->
<div class="modal-dialog modal-fullscreen-sm-down">
...
</div>
CSS
Variables
Added in v5.2.0As part of Bootstrap’s evolving CSS variables approach, modals now use local CSS variables on .modal
and .modal-backdrop
for enhanced real-time customization. Values for the CSS variables are set via Sass, so Sass customization is still supported, too.
--#{$prefix}modal-zindex: #{$zindex-modal};
--#{$prefix}modal-width: #{$modal-md};
--#{$prefix}modal-padding: #{$modal-inner-padding};
--#{$prefix}modal-margin: #{$modal-dialog-margin};
--#{$prefix}modal-color: #{$modal-content-color};
--#{$prefix}modal-bg: #{$modal-content-bg};
--#{$prefix}modal-border-color: #{$modal-content-border-color};
--#{$prefix}modal-border-width: #{$modal-content-border-width};
--#{$prefix}modal-border-radius: #{$modal-content-border-radius};
--#{$prefix}modal-box-shadow: #{$modal-content-box-shadow-xs};
--#{$prefix}modal-inner-border-radius: #{$modal-content-inner-border-radius};
--#{$prefix}modal-header-padding-x: #{$modal-header-padding-x};
--#{$prefix}modal-header-padding-y: #{$modal-header-padding-y};
--#{$prefix}modal-header-padding: #{$modal-header-padding}; // Todo in v6: Split this padding into x and y
--#{$prefix}modal-header-border-color: #{$modal-header-border-color};
--#{$prefix}modal-header-border-width: #{$modal-header-border-width};
--#{$prefix}modal-title-line-height: #{$modal-title-line-height};
--#{$prefix}modal-footer-gap: #{$modal-footer-margin-between};
--#{$prefix}modal-footer-bg: #{$modal-footer-bg};
--#{$prefix}modal-footer-border-color: #{$modal-footer-border-color};
--#{$prefix}modal-footer-border-width: #{$modal-footer-border-width};
--#{$prefix}backdrop-zindex: #{$zindex-modal-backdrop};
--#{$prefix}backdrop-bg: #{$modal-backdrop-bg};
--#{$prefix}backdrop-opacity: #{$modal-backdrop-opacity};
Sass variables
$modal-inner-padding: $spacer;
$modal-footer-margin-between: .5rem;
$modal-dialog-margin: .5rem;
$modal-dialog-margin-y-sm-up: 1.75rem;
$modal-title-line-height: $line-height-base;
$modal-content-color: null;
$modal-content-bg: $white;
$modal-content-border-color: var(--#{$prefix}border-color-translucent);
$modal-content-border-width: $border-width;
$modal-content-border-radius: $border-radius-lg;
$modal-content-inner-border-radius: subtract($modal-content-border-radius, $modal-content-border-width);
$modal-content-box-shadow-xs: $box-shadow-sm;
$modal-content-box-shadow-sm-up: $box-shadow;
$modal-backdrop-bg: $black;
$modal-backdrop-opacity: .5;
$modal-header-border-color: var(--#{$prefix}border-color);
$modal-header-border-width: $modal-content-border-width;
$modal-header-padding-y: $modal-inner-padding;
$modal-header-padding-x: $modal-inner-padding;
$modal-header-padding: $modal-header-padding-y $modal-header-padding-x; // Keep this for backwards compatibility
$modal-footer-bg: null;
$modal-footer-border-color: $modal-header-border-color;
$modal-footer-border-width: $modal-header-border-width;
$modal-sm: 300px;
$modal-md: 500px;
$modal-lg: 800px;
$modal-xl: 1140px;
$modal-fade-transform: translate(0, -50px);
$modal-show-transform: none;
$modal-transition: transform .3s ease-out;
$modal-scale-transform: scale(1.02);
Loop
Responsive fullscreen modals are generated via the $breakpoints
map and a loop in scss/_modal.scss
.
@each $breakpoint in map-keys($grid-breakpoints) {
$infix: breakpoint-infix($breakpoint, $grid-breakpoints);
$postfix: if($infix != "", $infix + "-down", "");
@include media-breakpoint-down($breakpoint) {
.modal-fullscreen#{$postfix} {
width: 100vw;
max-width: none;
height: 100%;
margin: 0;
.modal-content {
height: 100%;
border: 0;
@include border-radius(0);
}
.modal-header,
.modal-footer {
@include border-radius(0);
}
.modal-body {
overflow-y: auto;
}
}
}
}
Usage
The modal plugin toggles your hidden content on demand, via data attributes or JavaScript. It also overrides default scrolling behavior and generates a .modal-backdrop
to provide a click area for dismissing shown modals when clicking outside the modal.
Via data attributes
Toggle
Activate a modal without writing JavaScript. Set data-bs-toggle="modal"
on a controller element, like a button, along with a data-bs-target="#foo"
or href="#foo"
to target a specific modal to toggle.
<button type="button" data-bs-toggle="modal" data-bs-target="#myModal">Launch modal</button>
Dismiss
Dismissal can be achieved with the data
attribute on a button within the modal as demonstrated below:
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
or on a button outside the modal using the data-bs-target
as demonstrated below:
<button type="button" class="btn-close" data-bs-dismiss="modal" data-bs-target="#my-modal" aria-label="Close"></button>
Via JavaScript
Create a modal with a single line of JavaScript:
const myModal = new bootstrap.Modal(document.getElementById('myModal'), options)
// or
const myModalAlternative = new bootstrap.Modal('#myModal', options)
Options
As options can be passed via data attributes or JavaScript, you can append an option name to data-bs-
, as in data-bs-animation="{value}"
. Make sure to change the case type of the option name from “camelCase” to “kebab-case” when passing the options via data attributes. For example, use data-bs-custom-class="beautifier"
instead of data-bs-customClass="beautifier"
.
As of Bootstrap 5.2.0, all components support an experimental reserved data attribute data-bs-config
that can house simple component configuration as a JSON string. When an element has data-bs-config='{"delay":0, "title":123}'
and data-bs-title="456"
attributes, the final title
value will be 456
and the separate data attributes will override values given on data-bs-config
. In addition, existing data attributes are able to house JSON values like data-bs-delay='{"show":0,"hide":150}'
.
Name | Type | Default | Description |
---|---|---|---|
backdrop |
boolean, 'static' |
true |
Includes a modal-backdrop element. Alternatively, specify static for a backdrop which doesn’t close the modal when clicked. |
focus |
boolean | true |
Puts the focus on the modal when initialized. |
keyboard |
boolean | true |
Closes the modal when escape key is pressed. |
Methods
Asynchronous methods and transitions
All API methods are asynchronous and start a transition. They return to the caller as soon as the transition is started but before it ends. In addition, a method call on a transitioning component will be ignored.
Passing options
Activates your content as a modal. Accepts an optional options object
.
const myModal = new bootstrap.Modal('#myModal', {
keyboard: false
})
Method | Description |
---|---|
dispose |
Destroys an element’s modal. (Removes stored data on the DOM element) |
getInstance |
Static method which allows you to get the modal instance associated with a DOM element. |
getOrCreateInstance |
Static method which allows you to get the modal instance associated with a DOM element, or create a new one in case it wasn’t initialized. |
handleUpdate |
Manually readjust the modal’s position if the height of a modal changes while it is open (i.e. in case a scrollbar appears). |
hide |
Manually hides a modal. Returns to the caller before the modal has actually been hidden (i.e. before the hidden.bs.modal event occurs). |
show |
Manually opens a modal. Returns to the caller before the modal has actually been shown (i.e. before the shown.bs.modal event occurs). Also, you can pass a DOM element as an argument that can be received in the modal events (as the relatedTarget property). (i.e. const modalToggle = document.getElementById('toggleMyModal'); myModal.show(modalToggle) . |
toggle |
Manually toggles a modal. Returns to the caller before the modal has actually been shown or hidden (i.e. before the shown.bs.modal or hidden.bs.modal event occurs). |
Events
Bootstrap’s modal class exposes a few events for hooking into modal functionality. All modal events are fired at the modal itself (i.e. at the <div class="modal">
).
Event | Description |
---|---|
hide.bs.modal |
This event is fired immediately when the hide instance method has been called. |
hidden.bs.modal |
This event is fired when the modal has finished being hidden from the user (will wait for CSS transitions to complete). |
hidePrevented.bs.modal |
This event is fired when the modal is shown, its backdrop is static and a click outside of the modal is performed. The event is also fired when the escape key is pressed and the keyboard option is set to false . |
show.bs.modal |
This event fires immediately when the show instance method is called. If caused by a click, the clicked element is available as the relatedTarget property of the event. |
shown.bs.modal |
This event is fired when the modal has been made visible to the user (will wait for CSS transitions to complete). If caused by a click, the clicked element is available as the relatedTarget property of the event. |
const myModalEl = document.getElementById('myModal')
myModalEl.addEventListener('hidden.bs.modal', event => {
// do something...
})