I'm trying to vertically and horizontally center this div even when there is content to scroll and the user is scrolling down the page. The following test works fine in IE, but in Firefox I get a weird flickering affect when hovering over the thumbnail image. Any thoughts?
<html>
<head>
<title>aj</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
// img preview
$('.img').hover(function() {
if (!$('#overlay').length) {
$('<div id="overlay"/>').css({
position: 'fixed',
开发者_C百科 top: 0,
left: 0,
width: '100%',
zIndex: 100,
height: $(window).height() + 'px'
}).appendTo('body');
$('<div id="item" />').css({
border: '7px solid #999',
height: '500px',
width: '500px',
top: '50%',
left: '50%',
position: 'absolute',
marginTop: '-250px',
marginLeft: '-250px'
}).append('<img src="' + $(this).attr('rel') + '" alt="img" />').appendTo('#overlay');
}
}, function() {
$('#overlay').remove();
});
});
</script>
</head>
<body>
<img class="img" src="http://ajondeck.net/temp/paperboy_thumb.gif" rel="http://ajondeck.net/temp/paperboy.gif"
alt="image" />
</body>
</html>
foo.css
#container {
display: table;
width: 100%;
height: 100%;
}
#position {
display: table-cell;
width: 100%;
text-align: center;
vertical-align: middle;
}
foo.html
<html>
<head>
<link rel="stylesheet" href="foo.css" type="text/css">
<!--[if IE]>
<style type="text/css">
#container {
position: relative;
}
#position {
position: absolute; top: 50%;
}
#content {
position: relative;
top: -50%;
}
</style>
<![endif]-->
</head>
<body>
<div id="container">
<div id="position">
<div id="content">
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Donec laoreet egestas mi. Aliquam erat volutpat. Aliquam erat volutpat. Suspendisse potenti. Suspendisse potenti. Vestibulum mi nibh, hendrerit nec, feugiat vitae, feugiat a, nisl.
</div>
</div>
</div>
</body>
</html>
demo
http://www.vdotmedia.com/demo/css-vertically-center.html
Note: Horizontal centering should be a no sweat to handle on your own.
EDIT: I found another demo
EDIT: For this solution to work in HTML5, you'll need to add html, body { height:100% }
to your CSS (and obviously <!DOCTYPE HTML>
to the beginning of your HTML code).
精彩评论