How can I center a Bootstrap modal vertically and make it responsive?

Is there a way to vertically center the bootstrap modal? I have been searching for a solution, but none seem to be responsive or effective. My website is using Bootstrap 3.

The modal does not adjust properly on smaller screens or when the browser window is resized after applying the solution below.

Including jQuery:

$('.modal').on('shown.bs.modal', function() {
            $(this).find('.modal-dialog').css({
                'margin-top': function () {
                    return -($(this).outerHeight() / 2);
                },
                'margin-left': function () {
                    return -($(this).outerWidth() / 2);
                }
            });
        });

Applying CSS:

.modal-dialog {
        margin: 0;
        position: absolute;
        top: 50%;
        left: 50%;
    }

Using Bootstrap:

<!-- Button trigger modal -->
<button class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">
  Launch demo modal
</button>

<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" data-backdrop="false">
  <div class="modal-dialog custom-class">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
        <h4 class="modal-title" id="myModalLabel">Modal title</h4>
      </div>
      <div class="modal-body">
        ...
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div>
  </div>
</div>

Any suggestions?

EDIT:

I attempted the following CSS:

@media screen and (min-width: 768px) {
        .custom-class {
            width: 800px; /* either % (e.g. 60%) or px (400px) */
            top: 25%;
        }
    }

However, the modal defaults to its original position on smaller screens instead of being vertically centered as desired.

Additionally, top: 25%; does not fully center the modal vertically at all.

Answer №1

It seems like we've found the solution,

Cascading Style Sheets (CSS),

.modal-dialog {
        top: 0;
        margin-top: 0;
        display: none;
        border: 1px solid red;
    }

utilizing jQuery and Bootstrap frameworks,

$('#myModal').on('shown.bs.modal', function (e) {

            var object = $('.modal-dialog');
            var object_outerheight = object.outerHeight();
            var window_height = $(window).height();
            var window_scrolltop = $(window).scrollTop();
            var object_top = ((window_height - object_outerheight)/2) + window_scrolltop;
            console.log(object_top);

            // Adjusting the position of the object.
            object.css({
                marginTop: object_top + 'px'
            }).fadeIn();

            // Implementing responsiveness on window resize.
            $( window ).resize(function() {

                // Recalculating the dimensions upon resizing.
                var window_height = $(window).height();
                var window_scrolltop = $(window).scrollTop();
                var object_top = ((window_height - object_outerheight)/2) + window_scrolltop;
                console.log(object_top);

                // Realigning the object's position.
                object.css({
                    marginTop: object_top + 'px'
                });

            });
        });

Answer №2

One way to vertically center a Bootstrap modal is by using CSS.

    .modal {
        text-align: center;
        padding: 0!important;
    }

    .modal:before {
        content: '';
        display: inline-block;
        vertical-align: middle;
        margin: -2px;
        height: 100%;
    }

    .modal-dialog {
        display: inline-block;
        vertical-align: middle;
    }

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

Avoid triggering the onClick event on multiple submit buttons when the form data is deemed invalid by vee-validate

How can I ensure that the onClick event on a button is only called if certain input fields are valid, using vee-validate ValidationObserver? The validation should apply to individual buttons within a form, rather than the entire form itself, as there are m ...

What are the steps to automatically populate the location or name in the trip advisor widget?

I have encountered an issue with my website where I have multiple hotel lists but the trip advisor widget only shows one. Is there a solution, such as a script or other method, that can use variables to automatically set the location or name in the widget? ...

Material UI - Array of Chips

I have been working on creating a ReactJS component that displays an array of chips with unique styling for each one. To achieve this, I created individual makeStyles classes for the chips. However, I encountered difficulties in dynamically changing the cl ...

How can you set an input field to be initially read-only and then allow editing upon clicking a button using Vue.js?

//I have two divs that need to be set as readonly initially. When an edit button is clicked, I want to remove the readonly attribute and make them editable. <div> <input type="text" placeholder="<a href="/cdn-cgi/l/email-protection ...

Why do I need to control-click in order to download the link?

Lately, I have been operating a simple node.js server for hosting a website. However, recently, I encountered an issue where one of my download links began redirecting to the index.html page instead of initiating the download process for the PDF it is supp ...

Cautionary alert while displaying a data binding from a controller in AngularJS

Adding a numerical value to the controller: this.myValue = Number(elem.toFixed(2)); Then placing it inside an input form: <input class="my-input" type="number" value={{$ctrl.myValue}} ... > Although the value ...

Error 404 encountered while attempting to access dist/js/login in Node.JS bootstrap

I currently have a web application running on my local machine. Within an HTML file, I am referencing a script src as /node_modules/bootstrap/dist/js/bootstrap.js. I have configured a route in my Routes.js file to handle this request and serve the appropri ...

Why does jQuery treat an integer as a string when adding it to a variable?

While working on a for statement, I encountered an issue with adding an integer to a variable that increments. Strangely enough, the addition operation treats the integer as a string. However, other operations like subtraction or multiplication behave as e ...

Is it possible to change the src attribute after the page has loaded and execute it

A. I'm trying to figure out how to dynamically change the src attribute of an image using JavaScript after the page has loaded. <img src="http://example.com/image.png" /> to <img src="http://domain.com/different.jpg" /> B. Another questi ...

Attempting to retrieve JSON data using jQuery

Currently, I have a PHP file that outputs JSON data like the following: {"news":[{"title":"title news example1","content":"blabla bla 1","img":"url"}, {"title":"title news example2","content":"blabla bla 2","img":"url2"}, {"title":"title news example3","c ...

Managing data in Vuex by updating it from a child component using $emit

I'm currently working on a Vue app that has the capability to randomize a title and subtitle or allow users to manually edit these values using a custom input component. The challenge I'm facing is updating the parent component and state to refle ...

Guide on implementing two submission options in an HTML form using JavaScript

Currently, I am working on a form that includes two buttons for saving inputted data to different locations. However, I am facing an issue with the functionality of the form when it comes to submitting the data. Since only one submit function can be activa ...

Leveraging the Angular (2) routerLinkActive directive to handle dynamic routes

Although my current approach works, I believe there may be a more efficient way to implement this in Angular. The situation is as follows: Imagine nested, inflected paths like /logos and /logo/:id The markup below functions as intended: <li class ...

Adding Data Definition Language (DDL) statements while making an AJAX call

Is there a way to automatically update the value of a drop-down list whenever a partial view is loaded via an AJAX call? Currently, the AJAX call successfully retrieves the necessary information, but the user still needs to manually change the location val ...

The solution for fixing contenteditable is as follows:

I am currently working on a script to clean up pasted text within a contenteditable div. While the script is functioning well for most part, I have noticed that in Firefox, line breaks get removed when the text is copied within or between the divs. Does ...

``There seems to be an issue with the jquery swipe function not allowing navigation through elements in the

As I work on redesigning a website to optimize it for mobile devices, I wanted to incorporate swipe left and right navigation. After some research, I came across a jQuery example that seemed promising: Upon implementing this solution on my site, everythin ...

Perform bulk updates to various rows and columns based on their individual IDs within a Microsoft SQL Server

After extracting data from the database in Excel format using an SQL join query, I made modifications to some columns in the Excel sheet. Now, I need to update the modified data back into the database using the respective row IDs. However, when I try to it ...

Intercommunication of variables among components

My scenario involves two components, namely App and SomeComponent. I'm aiming to access a variable in App from SomeComponent. App: import React, { Component } from 'react'; import logo from './logo.svg'; import './App.css& ...

React Scroll and Material-UI button active link not functioning correctly

Whenever the link goes to the correct page, I want to add a special background effect or change the font color. Despite trying to use CSS for this purpose, it didn't work as intended. If you want to take a look at my code on codesandbox, follow this ...

The error of 'illegal invocation' occurs when attempting to use input setCustomValidity with TypeScript

I am new to the Typescript world and currently converting one of my first React applications. I am facing an issue while trying to set custom messages on input validation using event.target.setCustomValidity. I keep getting an 'Illegal invocation&apo ...