Ways to center Bootstrap v4 modal pop-ups vertically

How to properly center Bootstrap 4 modal dialogues vertically?

Please Note: I am seeking a precise method to vertically center a Bootstrap modal that covers all scenarios, on all devices, and in all browsers. I needed this for a large single-page application where the same modal is used throughout, so it needed to function correctly in every instance.

The method must:

  • Ensure modal contents remain accessible, even on devices with smaller screens
  • Work on any device and browser with a market share exceeding 1%
  • Avoid using display:table-cell or other layout-hacking techniques
  • Close when clicked or tapped outside of the .modal-content section
  • Minimize the need for jQuery/JavaScript
  • (optional) Be compatible with default Bootstrap examples without requiring modifications to the markup

Answer №1

Update: In the latest release, Beta 3, you can now center the modal vertically by adding the class .modal-dialog-centered to .modal-dialog. For more details, refer to the documentation.


Here is the original answer:

SCSS:

.modal-dialog {
  min-height: calc(100vh - 60px);
  display: flex;
  flex-direction: column;
  justify-content: center;
  overflow: auto;
  @media(max-width: 768px) {
    min-height: calc(100vh - 20px);
  }
}

or unprefixed CSS:

.modal-dialog {
    min-height: calc(100vh - 60px);
    display: flex;
    flex-direction: column;
    justify-content: center;
    overflow: auto;
}
@media(max-width: 768px) {
  .modal-dialog {
    min-height: calc(100vh - 20px);
  }
}

Note 1: Keep in mind that fully prefixed CSS may become obsolete as browser support changes. To get the latest prefixed CSS, input the unprefixed code into Autoprefixer, adjust the settings, and grab the updated CSS.

Note 2: This answer was originally added during the early stages of v4 (alpha 3 or 4), which is now in the beta phase. You can enhance the CSS by adding the following classes to .modal-dialog:

h-100 d-flex flex-column justify-content-center my-0

As noted by @Androbaut in the comments below, you will still need the JavaScript (see below) to close the modal on click or tap outside the modal window.


jQuery (required for modal closing on click/tap):

$('.modal-dialog').on('click tap', function(e){
  if ($(e.target).hasClass('modal-dialog')) {
    $('.modal').modal('hide');
  }
})

And that's all you need!


For a working sample, fully-prefixed CSS, and markup with various modal sizes, refer to the code snippet above. If you encounter any issues or have suggestions for improvement, feel free to share. Your feedback is valuable in enhancing the content.

Answer №2

To center a modal using bootstrap, you can simply add the modal-dialog-centered class along with model-dialog as shown below:

<head>
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
  <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
</head>
 <button class="btn btn-success" data-toggle="modal" data-target="#MyModal">Launch Modal</button>     
<div class="modal align-middle" id="MyModal">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Modal Title</h5>
                <button class="close" data-dismiss="modal">&times;</button>
            </div>
            <div class="modal-body">Lorem Ipsum is simply dummy text of the                        printing and typesetting industry</div> 
            <div class="modal-footer">
                <button class="btn btn-info" data-dismiss="modal">Close</button>
            </div>                
        </div>
    </div>
</div>

Answer №3

Here is an easy technique using Flexbox.

Using SCSS

.modal-open .modal {
    display: flex!important;
    align-items: center!important;
    .modal-dialog {
        flex-grow: 1;
    }
}

View Working Demo

Answer №4

To easily center a modal on the screen vertically, you can simply add the class "modal-dialog-centered".

For example:

<div class="modal-dialog modal-dialog-centered" role="document">

Thank you.

Answer №5

If you have small or lengthy modals that require scrolling, you can use this solution.

Simply apply the following custom CSS rules:

.modal-header {
  flex-shrink: 0;
}

.modal-body {
  overflow-y: auto;
}

Also, don't forget to add the following classes:

  • To modal-dialog:
    h-100 my-0 mx-auto d-flex flex-column justify-content-center
  • To modal-content: m-2

Here is an example of how to implement these classes:

<div class="modal-dialog h-100 my-0 mx-auto d-flex flex-column justify-content-center" role="document">
  <div class="modal-content m-2">
     ...
  </div>
</div>

Answer №6

To center the modal vertically, just add the class .modal-dialog-centered to the .modal-dialog.

<!-- Trigger the modal with a button -->
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModalCenter">
  Launch demo modal
</button>

<!-- Modal -->
<div class="modal fade" id="exampleModalCenter" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLongTitle">Modal title</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        ...
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div>
  </div>
</div>

Answer №7

If you're experiencing issues with your modal, try incorporating the following CSS into your '.modal-dialog' class. Feel free to customize with your own CSS class as needed.

.modal-dialog {
      height: 100vh;
      display: flex;
      align-items: center;
}

Answer №8

To easily center your modal vertically, you can adjust the top: 50%;, transform: translateY(-50%);, and margin: 0 auto; properties in the modal dialog class.

Note: It is important to also add max-height: 100vh; to the .modal-content class to ensure that the top of the modal remains accessible even when the modal height exceeds the viewport.

Check out this demo for reference:

.modal.vertically-centered .modal-dialog {
  transform: translateY(-25%);
  top: 50%;
  margin: 0 auto;
}

.modal.vertically-centered.show .modal-dialog {
  transform: translateY(-50%);
}

.modal-content {
  max-height: 100vh;
  overflow-y: auto;
  padding: 40px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js "></script>

<button class="btn btn-primary" data-toggle="modal" data-target=".vertically-centered">Show modal</button>

<div class="modal fade vertically-centered" tabindex="-1" role="dialog" aria-hidden="true">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      Vertically centered modal
    </div>
  </div>
</div>

Answer №9

There's a simpler method to achieve this without the need for excessive CSS overrides or custom CSS. By utilizing the stock bootstrap classes and adding an additional HTML element to control the height, you can achieve the desired outcome.

CSS (No Longer Required - Refer Below)

.modal > .row{
    flex: 1;
}

HTML (Revised - See Below)

<div id="dialogBox" class="modal fade d-flex">
    <div class="row justify-content-center"> <!-- Vertically Align Modal -->
        <div class="modal-dialog align-self-center" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Modal title</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <p>Modal body text goes here.</p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-primary">Save changes</button>
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                </div>
            </div>
        </div>
    </div>
</div>

Usage Instructions:


JS

$("#dialogBox").modal('show');

OR HTML

<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#dialogBox">
  Launch demo modal
</button>

Although it's possible to achieve the desired outcome using only the bootstrap classes .row, .col, and flex-XXX, I struggled to make it work effectively.

Lastly, it may be necessary to add: <body class="d-flex"> depending on your existing CSS for everything to function correctly.

UPDATE


An alternative way to achieve this is by utilizing only bootstrap classes h-100 and w-100:

<div id="dialogBox" class="modal fade d-flex">
    <div class="row justify-content-center w-100"> <!-- Vertically Align Modal -->
        <div class="modal-dialog align-self-center" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Modal title</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <p>Modal body text goes here.</p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-primary">Save changes</button>
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                </div>
            </div>
        </div>
    </div>
</div>

Answer №10

Give this a shot:

::ng-deep{
    .modal-body{
        padding: 0.25rem;
        width: 600px !important;
    }
    .modal-content {
        position: relative;
        display: flex;
        flex-direction: row;
        margin-top: auto;
        margin-bottom: auto;
        width: 600px !important;
      }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Struggling to position a div below another div within a flex box layout

https://i.sstatic.net/8vZSW.jpg When trying to make the Information & advice header appear above the other div elements, I encountered an issue with flexbox. Despite setting the container div to have a flex direction of column, the header div continue ...

Establish the dimensions of the element to match the dimensions of a responsive image

Currently, I am working on implementing flippable images on my website. It is important to me that the "back" of these images matches the dimensions of the front image. The challenge I am facing is that I have applied the Bootstrap img-responsive class to ...

Unused content in the stylesheet

I am currently referencing my CSS stylesheet in the following way: <link rel="stylesheet" type="text/css" href='@routes.Assets.versioned("stylesheets/main.css")' media="screen" /> The location of the stylesheet is found at /public/stylesh ...

Guide to personalizing the ngxDaterangepickerMd calendaring component

I need to customize the daterangepicker library using ngxDaterangepickerMd in order to separate the start date into its own input field from the end date. This way, I can make individual modifications to either the start date or end date without affectin ...

Secret icon revealing on mouseover

I devised a simple technique to showcase an element overlapping another, like an overlay, and it was functioning flawlessly until the point where I needed to incorporate a "button" (styled as a Bootstrap anchor) beneath it. Here is the initial setup and h ...

What is the best way to conceal the li elements that exceed a single line?

I have a unordered list containing product information as list items. My goal is to hide the list items that do not fit on a single line based on the screen size. Therefore, the number of products displayed should adjust depending on how many can fit on a ...

Using a combination of CSS selector, several attributes, and the OR operator

Can you assist me with CSS selectors? Let's say we have a style HTML tag: <style type="text/css"> [...selector...] {color:red;} </style> I want to create a selector with multiple attributes and logical operators, but I am uncertain about ...

What is the best way to align a box once another one has been placed?

I have integrated both Bootstrap and Masonry plugins into my website design. The issue I am facing is that the Masonry plugin box goes under the top Bootstrap bar. I tried adding a margin-top: 50, but this resulted in a horizontal scroll bar appearing. To ...

Guide on validating a dropdown using template-driven forms in Angular 7

Having trouble validating a dropdown select box, possibly due to a CSS issue. Any suggestions on how to fix this validation problem? Check out the demo here: https://stackblitz.com/edit/angular-7-template-driven-form-validation-qxecdm?file=app%2Fapp.compo ...

Create dynamic Bootstrap 4 menus featuring three levels of navigation - the initial dropdown sub-menu may not display any selectable options

Using Bootstrap 4 and jQuery 2.2.4, I've created a navbar with three layers of menus, comprising two levels of drop-downs from the top-most level. Everything works smoothly except for a glitch on mobile devices. The menu collapses to the hamburger ic ...

Connecting Angular TextArea functionality to the Ctrl-Enter keyboard shortcut

Recently, I've been working on creating a custom functionality for the <textarea> element. My goal is to have the enter key trigger a specific function, while using ctrl+enter will add a new line in the textarea. I've tried looking through ...

Creating a li active shape involves defining styles for the active state of

I'm having trouble creating a shape in the menu header to show that it's selected with an active class. I've been struggling to bring the shape up and align it properly. Here is what I have attempted: HTML <li class="active"&g ...

For a while now, I've been attempting to transform my paragraph into a block within a section that showcases elements in an inline-flex layout

I have been attempting to adjust the paragraph with the errorDate class so that it displays as a block element directly beneath the input element similar to the image provided here. The section is currently set to appear as an inline-flex. Below is the CS ...

Avoid loading the background image by utilizing CSS to set the background image

Whenever I attempt to assign a background image using CSS, it triggers a console error. This is my CSS code: body { background-image: url("background.png"); background-repeat: no-repeat; } The error message displayed is: GET http://localhost/myWeb/ ...

I am in need of a datepicker for my project that will display the END date as the current date and set the START date as 7 days before the END date

$(document).ready(function () { $("#end").datepicker({ dateFormat: "dd-M-yy", minDate: 0, onSelect: function () { var start = $('#start'); var startDate = $(this).datepicker('getDate') ...

What is the best way to make a div span the entire height of the body?

I have a menu that I want to wrap inside a yellow div. The yellow div should take up the entire height of the green square, regardless of the content size in the green square. For example, if the orange square expands, the yellow div should also expand. h ...

Incorporating an image prior to the "contains" term with the help of JavaScript

Seeking assistance with the code snippet below without altering the text targeted in my "a:contains" statement. The challenge lies in determining the appropriate placement of ::before in the script provided. Link: https://jsfiddle.net/onw7aqem/ ...

Is there a way to implement CSS transitions when hiding elements?

My bootstrap navbar collapses and displays items outside of it. However, when I hide the menu, the overlay div disappears immediately and does not transition smoothly with the menu. How can I apply a transition to the div when hiding the menu? I've t ...

Utilizing Selenium with Java, you can hover over a button and choose to click on any of the available options

Currently, I am utilizing Selenium to automate the user interface using Java. Within the UI, there is an action button that, when hovered over by the User, displays two clickable options - Create and Edit. For ease of use, I have stored CSS locators as E ...

Turn an item by x degrees, not towards x degrees

Is there a way to rotate an object by a specific degree, rather than to a specific degree? I am familiar with using transform/-webkit-transform to rotate an object by a set degree, but I am looking for a method that will rotate my object by the specified ...