Reputation: 166
I am having some problem centering a modal, when i am using serverel modals on the same page.
So whenever i press the button within the circle, the modal opens. On the page there are 6 modals, each with unique ID's of course.
On the image below, you see that the first model is centeret - simply using hacks for this.
However when i press another model to pop-up, it is not centered as seen below:
So as i see it, the javascript doesn't take into account the width of the screen or something like that.
The following is the CSS for the modal:
element {
opacity: 1;
visibility: visible;
left: 50%;
}
.reveal-modal {
top: -180px !important;
width: 750px;
background: url("modal-gloss.png") no-repeat scroll -200px -80px #EEE;
position: absolute;
z-index: 101;
padding: 30px 40px 34px;
border-radius: 5px;
}
As you can see, i am using percentages, however the problem still occurs. What is it, that is going wrong with this modal, since it doesn't center all the modals?
Upvotes: 2
Views: 7405
Reputation: 21758
Since you're already positioning .reveal-modal
absolutely all you need to do is set a proper offset to counter your left: 50%
value.
Try setting margin-left: -375px
on .reveal-modal
. This is exactly half of the width (750px
) of that element.
Upvotes: 1
Reputation: 37711
If you want to center an absolutely positioned element, here's the code that works every time, no hacks needed (no negative margins combined with 50% offsets), it's always vertically and horizontally centered inside its parent:
.element {
left: 0;
right: 0;
top: 0;
bottom: 0;
margin: auto;
position: absolute;
}
See it here:
.element {
left: 0;
right: 0;
top: 0;
bottom: 0;
margin: auto;
position: absolute;
width: 100px;
height: 100px;
background: #eee;
}
<div class="element">Centered</div>
Upvotes: 8
Reputation: 787
Do something like this for a modal popup:
HTML:
<div class="wrap">
<div class="modal"></div>
</div>
CSS:
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
.wrap {
position: absolute;
width: 100%;
height: 0;
top: 50%;
border: 1px solid blue;
}
.modal {
position: relative;
margin: auto;
border: 1px solid red;
width: 100px;
height: 200px;
top: -100px;
}
Fiddle: http://jsfiddle.net/jpvLf87x/
In the top: -100px;
part, the -100px should be half of the popups height, so if the popup is 500px tall, it should have top: -250px
instead. The margin: auto
will automatically center it horizontally no matter the width
Upvotes: 0