最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to center modal to the center of screen? - Stack Overflow

programmeradmin8浏览0评论

How to center modal to the center of screen? This is my html and js code It works in Chrome console, but when I refresh this page - it doesn't work

$('.modal').css('top', $(window).outerHeight() / 2 - ($(".modal-dialog").outerHeight()) / 2 + 'px');

How to center modal to the center of screen? This is my html and js code It works in Chrome console, but when I refresh this page - it doesn't work

$('.modal').css('top', $(window).outerHeight() / 2 - ($(".modal-dialog").outerHeight()) / 2 + 'px');
Share Improve this question edited Sep 21, 2016 at 23:33 Tilendor 48.9k17 gold badges53 silver badges58 bronze badges asked Sep 21, 2016 at 22:33 Vlad UdodVlad Udod 1,7292 gold badges11 silver badges9 bronze badges 2
  • Are you using Bootstrap ? If yes, check this answer – Robiseb Commented Sep 21, 2016 at 22:40
  • 1 Pure JavaScript : stackoverflow.com/a/62282447/11258866 – Hasan_Naser Commented Jun 9, 2020 at 12:22
Add a comment  | 

13 Answers 13

Reset to default 108

Easy way to solve

.center {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
}

There is no need for jQuery, you can accomplish that just using css:

body {
  background: gray;
}

.modal {
  background: green;
  position: absolute;
  float: left;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
}
<div class="modal">
  Lorem ipsum
</div>

If you prefer jQuery solution here is it:

$(function() {
  var modal = $(".modal");
  var body = $(window);
  // Get modal size
  var w = modal.width();
  var h = modal.height();
  // Get window size
  var bw = body.width();
  var bh = body.height();
  
  // Update the css and center the modal on screen
  modal.css({
    "position": "absolute",
    "top": ((bh - h) / 2) + "px",
    "left": ((bw - w) / 2) + "px"
  })
});
body {
  background: gray;
}

.modal {
  background: green;
  float: left;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="modal">
  Lorem ipsum
</div>

If you are using Bootstrap modals, all you need to do is add the .modal-dialog-centered class to the modal dialog. See below

Change this line <div class="modal-dialog" role="document">

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

Try like this

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

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

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

if you prefer jquery means try this

function setModalMaxHeight(element) {
  this.$element     = $(element);  
  this.$content     = this.$element.find('.modal-content');
  var borderWidth   = this.$content.outerHeight() - this.$content.innerHeight();
  var dialogMargin  = $(window).width() < 768 ? 20 : 60;
  var contentHeight = $(window).height() - (dialogMargin + borderWidth);
  var headerHeight  = this.$element.find('.modal-header').outerHeight() || 0;
  var footerHeight  = this.$element.find('.modal-footer').outerHeight() || 0;
  var maxHeight     = contentHeight - (headerHeight + footerHeight);

  this.$content.css({
      'overflow': 'hidden'
  });

  this.$element
    .find('.modal-body').css({
      'max-height': maxHeight,
      'overflow-y': 'auto'
  });
}

$('.modal').on('show.bs.modal', function() {
  $(this).show();
  setModalMaxHeight(this);
});

$(window).resize(function() {
  if ($('.modal.in').length != 0) {
    setModalMaxHeight($('.modal.in'));
  }
});

Centering the modal is fairly simple if you use the CSS calc() function on the left CSS property. Let's say that the modal has a width of 600px. You can use 50% of the screen width minus half of the width for the modal. This example below has the modal at 600px so I have the calc() function at 50% - 300px.

#modal {
   position:  fixed;
   width: 600px;
   top: 40px;
   left: calc(50% - 300px);
   bottom: 40px;
   z-index: 100;
}

simply add below class "modal-dialog-centered" like below

<div class="modal center" tabindex="-1" id="tourBookModal">
  <div class="modal-dialog modal-lg modal-dialog-centered">
       <div class="modal-content"></div>
  </div>
</div>

you should rewrite the css class for modals and modals dialog as this :

.modal-dialog {
  display: flex !important;
  width: 50% !important;
  pointer-events: none;
  justify-content: center;
  align-items: center;
}
.modal{
  display:flex !important;
}

Pure Javascript

This code helps you in all scenarios

 var setDivCenter = function (classORid) {

        var div = document.querySelector(classORid);

        var Mwidth = div.offsetWidth;
        var Mheight = div.offsetHeight;
        var Wwidth = window.innerWidth;
        var Wheight = window.innerHeight;

        div.style.position = "absolute";
        div.style.top = ((Wheight - Mheight ) / 2 +window.pageYOffset ) + "px";
        div.style.left = ((Wwidth - Mwidth) / 2 +window.pageXOffset ) + "px";

    };

Please try this it works.

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

Add below code in js file. Note: "#mydialog" change to your selector(Dialog class or ID)

$(function() {
    $(window).resize(function(event) {
        $('#mydialog').position({
                my: 'center',
                at: 'center',
                of: window,
                collision: 'fit'
	         });
	    });
});	

Thanks, Anand.

.modal-dialog {
  height: 100%;
  width: 600px;
  display: flex;
  align-items: center;
}

.modal-content {
  margin: 0 auto;
}

Try something like:

$('.modal').css('margin-top', (Math.floor((window.innerHeight - $('.modal')[0].offsetHeight) / 2) + 'px');

// Get the modal
const modal = document.getElementById("myModal");

// Get the button that opens the modal
const btn = document.getElementById("myBtn");

// Get the <span> element that closes the modal
const span = document.getElementsByClassName("close")[0];

// When the user clicks the button, open the modal 
btn.onclick = function() {
  modal.style.display = "block";
}

// When the user clicks on <span> (x), close the modal
span.onclick = function() {
  modal.style.display = "none";
}

// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
  if (event.target == modal) {
    modal.style.display = "none";
  }
}
body {font-family: Arial, Helvetica, sans-serif;}

/* The Modal (background) */
.modal {
  display: flex;/* Hidden by default */
  justify-content:center;
  align-items:center;
  position: fixed; /* Stay in place */
  z-index: 1; /* Sit on top */
  left: 0;
  top: 0;
  width: 100%; /* Full width */
  height: 100%; /* Full height */
  overflow: auto; /* Enable scroll if needed */
  background-color: rgb(0,0,0); /* Fallback color */
  background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
}

/* Modal Content */
.modal-content {
  background-color: #fefefe;
  margin: auto;
  padding: 20px;
  border: 1px solid #888;
  width: 80%;
}

/* The Close Button */
.close {
  color: #aaaaaa;
  float: right;
  font-size: 28px;
  font-weight: bold
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">

</head>
<body>

<h2>Modal Example</h2>

<!-- Trigger/Open The Modal -->
<button id="myBtn">Open Modal</button>

<!-- The Modal -->
<div id="myModal" class="modal">

  <!-- Modal content -->
  <div class="modal-content">
    <span class="close">&times;</span>
    <p>Some text in the Modal..</p>
  </div>

</div>
</body>

发布评论

评论列表(0)

  1. 暂无评论