I’m trying to horizontally and vertically center a modal window inside a div. I want it to be cross browser compatible. You can see from the picture below that when I resize IE8 then click, “show modal” button it displays not exactly horizontally centered. This does not seem to be an issue with Chrome. Any thoughts? How would you guys accomplish this?
<html>
<head>
<title>test</title>
<style type="text/css">
*
{
margin: 0px;
padding: 0px;
}
</style>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$('#modal').click(function() {
// overlay
$('<div id="overlay" />').css({
position: 'absolute',
top: 0,
left: 0,
width: '100%',
height: '100%',
backgroundColor: 'black',
opacity: 0
}).appendTo('body');
$('<div id="datamodal" />').css({
backgroundColor: '#FFFFFF',
border: '10px solid #999',
height: '200px',
width: '600px',
position: 'absolute',
top: '50%',
left: '50%',
marginTop: '-120px',
marginLeft: '-320px',
color: '#111111',
fontWeight: 'bold',
padding: '10px',
display: 'none'
}).append('<input type="text" />').appendTo('#overlay');
$('#overlay').fadeTo(300, 0.7);
$('#datamodal').fadeIn(300);
});
});
</script>
</head>
<body>
<input id="modal" type="button" value="show modal" />
</body>
</html>
After messing around with the CSS for a long time and scratching my head, I noticed that the document doesn’t have a DOCTYPE. I added a Strict DOCTYPE and suddenly IE8 started behaving with the rest of your code untouched.