在制作网页过程中,通常通过以下方法,来实现网页水平垂直居中:
<div style=" width:900px; height:600px; position:absolute; top:50%; left:50%; margin-top:-300px; margin-left:-450px;"></div>
然而,在一些分辨率比较小的电脑,这样的方法,会使网页被截去一部分,比如在800*600的分辨率,虽然现在已经普遍不用800*600的分辨率了,但是在以下条件比较差的地方,还是有人在使用800*600.所以我们在设计过程中,一定要考虑到不同分辨率的问题.
那么,如果上面的方法有问题的话,我们可以通过写一段JAVASCIRPT来调用不同的CSS.
以下是JAVASCRIPT的代码:
<!--
function getBrowserWidth(){
if (window.innerWidth){
return window.innerWidth;}
else if (document.documentElement && document.documentElement.clientWidth != 0){
return document.documentElement.clientWidth; }
else if (document.body){return document.body.clientWidth;}
return 0;
}
//--><!--
function determineStyle(){
var browserWidth = getBrowserWidth();
var i, a, main;
if (browserWidth <= 995){
for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
if(a.getAttribute("rel").indexOf("style") != -1
&& a.getAttribute("title")) {
a.disabled = true;
if(a.getAttribute("title") == "narrow") a.disabled = false;
}
}
}
if (browserWidth > 995){
for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
if(a.getAttribute("rel").indexOf("style") != -1
&& a.getAttribute("title")) {
a.disabled = true;
if(a.getAttribute("title") == "wide") a.disabled = false;
}
}
}
}
//-->
<!--
function doOnResize () {
determineStyle();
}
function doOnLoad () {
determineStyle();
if ( getCookie("externalLinks") ) {
setLinkAttributes( getCookie("externalLinks") );
}}
window.onresize = doOnResize;
window.onload = doOnLoad;
//-->
以下是CSS的代码:
适用于1024*768及其以上分辨率的:
width:900px; height:600px; position:absolute; top:50%; left:50%; margin-top:-300px; margin-left:-450px;
适用于800*600分辨率的:
width:900px;(即网页的宽度)
在html页面分别引入CSS:
<link id="wide" title="wide" media="screen" href="css/1024.css" rel="stylesheet" type="text/css" />
<link id="narrow" title="narrow" media="screen" href="css/800.css" rel="alternate stylesheet" type="text/css" />
这样就可以在高分分辨率下实现水平居中,在低分辨率下,又不会有网页被截掉一部分的问题!
网页水平垂直居中在不同分辨率的实现方法
