Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
175
rated 0 times [  179] [ 4]  / answers: 1 / hits: 57861  / 14 Years ago, thu, july 8, 2010, 12:00:00

How to align a pop up division to center of monitor/screen using javascript?



I tried using screen.width and screen.height to get center. But the division gets aligned to center of scrolling page vertically



Thanks in advance for any help and suggestions


More From » javascript

 Answers
2

Try this:



<div id=popup class=popup>
This a vertically and horizontally centered popup.
</div>

<a onclick=showPopup('popup');>Show Popup</a>

<style type=text/css>
.popup {
width:200px;
height:100px;
position:absolute;
top:50%;
left:50%;
margin:-50px 0 0 -100px; /* [-(height/2)px 0 0 -(width/2)px] */
display:none;
}
</style>

<script type=text/javascript>
function showPopup(id) {
var popup = document.getElementById(id);
popup.style.display = 'block';
}
</script>


CSS explained:
The div is 200x100, you position it 50% from the top and 50% from the left, but to have it centered fully, you need to substract from that 50% values the half of the width and height, the way to do this is to use negative margins, hence margin-top should be the negative value of the height/2 and margin-left should be the negative value of the width/2.


[#96306] Sunday, July 4, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ronniem

Total Points: 584
Total Questions: 111
Total Answers: 111

Location: Finland
Member since Sat, Nov 6, 2021
3 Years ago
ronniem questions
Sat, Apr 24, 21, 00:00, 3 Years ago
Wed, Mar 10, 21, 00:00, 3 Years ago
Sat, Feb 6, 21, 00:00, 3 Years ago
;