I'm working with a bootstrap modal and want to center it (width and height based on window width/height).
I've tried this:
(function(global) {
let W = $(global).width(),
H = $(global).height();
// console.log($('.modal .modal-content').width()); // -2
// console.log($('.modal .modal-content').height()); // -2
$('.modal').on('shown.bs.modal', function() {
let $content = $(this).find('.modal-content');
let w = $content.width(),
h = $content.height();
$content.css({
'margin-left': (W / 2) - (w / 2),
'margin-top': (H / 2) - (h / 2)
});
});
}(window));
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">
Launch demo modal
</button>
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></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>
It works. But the problem
(for me) is: the code doesn't center the modal before showing. I want to center it first. I've also tried with show.bs.modal
but it makes something wrong.
Then, I'm trying to get the content width and height before loading:
console.log($('.modal .modal-content').width()); // -2
console.log($('.modal .modal-content').height()); // -2
The modal has been appended to the body tag successful, but I'm not still getting the width and height.
Where can I edit? Thank you!