Reputation: 19305
I have seen solutions for limiting a modal's width to a certain percent of the page or to a certain column span, but is it possible to simply get the modal to best fit - that is use the minimal width of the modal content?
I tried to add width: auto;
without success.
See:
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-hidden="true" style="width:auto">
<div class="modal-dialog" style="width:auto">
<div class="modal-content">
<img src="http://pdf.buildasign.com/upload/images/templateImages/TC17819031-42-260-195-7357-11-SharedDesign.png">
<br>
<p>hello</p>
</div>
</div>
</div>
I would like the modal width to be that of the top banner (plus some margin), the modal to be centered and the width/centering to maintain itself if the page width changes.
Thanks!
Upvotes: 0
Views: 1703
Reputation: 19305
Here's a comprehensive solution, saving the original width and using it to calculate width and left-margin percent on shown event and doc resize. Hiding the dialog initially to prevent the flicker effect.
<button class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">Launch</button>
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content" style="display:none;">
<img src="http://pdf.buildasign.com/upload/images/templateImages/TC17819031-42-260-195-7357-11-SharedDesign.png">
<br>
<p>hello</p>
</div>
</div>
function hCenterModals() {
function toP(n) { return (n * 100).toFixed() + '%'; }
$('.modal').each(function () {
var modalDialog = $(this).find('.modal-dialog'),
modalContent = $(this).find('.modal-content');
// get/save minWidth to data (for resize)
var minWidth = modalDialog.data('minWidth');
if (!minWidth) {
minWidth = modalContent.width();
if (minWidth > 0) {
modalDialog.data('minWidth', minWidth);
console.log('saved ' + minWidth);
} else {
minWidth = 0;
}
}
if (minWidth>0 && modalDialog.is(':visible')) {
var widthFrac = minWidth / $(window).width();
modalDialog.css({
'width': toP(widthFrac),
'margin-left': toP((1 - widthFrac) / 2)
});
}
});
}
$('#myModal').on('shown.bs.modal', function (e) {
hCenterModals();
var modalContent = $(this).find('.modal-content');
modalContent.show();
});
$(window).resize(hCenterModals).trigger("resize");
see jsfiddle
Upvotes: 1
Reputation: 21231
You'll need to handle the shown.bs.modal
event, and resize the div to whatever, like so:
http://jsfiddle.net/vyw2zvfu/2/
$(function(){
$('#myModal').on('shown.bs.modal', function(e){
var width = $(this).find('.modal-content img').width();
$(this).animate({ 'width': width+25 });
});
});
You'll notice that the modal starts at it's default size, however.
Upvotes: 2