我需要的是在屏幕中间显示网页的内容,无论屏幕尺寸大小,分辨率高或低,它都会自动调整到屏幕中间。< / p>
答案 0 :(得分:47)
无论浏览器窗口大小如何,我都猜测你想要将盒子垂直和水平居中。由于您有一个固定的宽度和高度的框,这应该工作:
<强>标记:强>
<div></div>
<强> CSS:强>
div {
height: 200px;
width: 400px;
background: black;
position: fixed;
top: 50%;
left: 50%;
margin-top: -100px;
margin-left: -200px;
}
即使您调整浏览器大小,div也应保留在屏幕的中央。只需将边距顶部和边距左侧替换为桌子高度和宽度的一半即可。
编辑:信用转到CSS-Tricks,我得到了最初的想法。
答案 1 :(得分:4)
您发布的代码的解决方案:
.center{
position:absolute;
width:780px;
height:650px;
left:50%;
top:50%;
margin-left:-390px;
margin-top:-325px;
}
<table class="center" width="780" border="0" align="center" cellspacing="2" bordercolor="#000000" bgcolor="#FFCC66">
<tr>
<td>
<table width="100%" border="0">
<tr>
<td>
<table width="100%" border="0">
<tr>
<td width="150"><img src="images/banners/BAX Company.jpg" width="149" height="130" /></td>
<td width="150"><img src="images/banners/BAX Location.jpg" width="149" height="130" /></td>
<td width="300"><img src="images/banners/Closet.jpg" width="300" height="130" /></td>
<td width="150"><img src="images/banners/BAX Company.jpg" width="149" height="130" /></td>
<td width="150"><img src="images/banners/BAX Location.jpg" width="149" height="130" /></td>
</tr>
</table>
</td>
</tr>
<tr>
<td>
<table width="100%" border="0">
<tr>
<td width="150"><img src="images/banners/BAX Company.jpg" width="149" height="130" /></td>
<td width="150"><img src="images/banners/BAX Location.jpg" width="149" height="130" /></td>
<td width="300"><img src="images/banners/Closet.jpg" width="300" height="130" /></td>
<td width="150"><img src="images/banners/BAX Company.jpg" width="149" height="130" /></td>
<td width="150"><img src="images/banners/BAX Location.jpg" width="149" height="130" /></td>
</tr>
</table>
</td>
</tr>
</table>
-
这是如何运作的?
<div class="center">
Lorem ipsum
</div>
.center{
position:absolute;
height: X px;
width: Y px;
left:50%;
top:50%;
margin-top:- X/2 px;
margin-left:- Y/2 px;
}
要垂直和水平定位div
,请将 X 和 Y 除以 2 。
答案 2 :(得分:3)
如果您想要水平和垂直居中,但之前不知道您的网页有多高,则必须使用JavaScript。
HTML:
<body>
<div id="content">...</div>
</body>
CSS:
#content {
max-width: 1000px;
margin: auto;
left: 1%;
right: 1%;
position: absolute;
}
JavaScript(使用jQuery):
$(function() {
$(window).on('resize', function resize() {
$(window).off('resize', resize);
setTimeout(function () {
var content = $('#content');
var top = (window.innerHeight - content.height()) / 2;
content.css('top', Math.max(0, top) + 'px');
$(window).on('resize', resize);
}, 50);
}).resize();
});
答案 3 :(得分:0)
<强> HTML 强>
<!DOCTYPE html>
<html>
<head>
<title>Center</title>
</head>
<body>
<div id="main_body">
some text
</div>
</body>
</html>
<强> CSS 强>
body
{
width: 100%;
Height: 100%;
}
#main_body
{
background: #ff3333;
width: 200px;
position: absolute;
}
JS(jQuery)
$(function(){
var windowHeight = $(window).height();
var windowWidth = $(window).width();
var main = $("#main_body");
$("#main_body").css({ top: ((windowHeight / 2) - (main.height() / 2)) + "px",
left:((windowWidth / 2) - (main.width() / 2)) + "px" });
});
参见示例here