查了很多很多,想法都是好的,想只用CSS实现兼容各种浏览器的垂直居中,但是我看了效果都不是很理想。
后来猛一拍脑门,要想在所有浏览器里都实现垂直居中,简单几句JS(要借助JQuery)就可以了。
原理就是根据id取得myheight和myfatherheight,然后再设置要被居中的元素的top值,OK,搞定。
<
script
src
="scripts/jquery.js"
type
="text/javascript"
></
script
>
< script type ="text/javascript" >
$(document).ready( function () {
FixIt_Vertically( " div1 " );
});
function FixIt_Vertically(id) {
// var myobj = document.getElementById(id);
var myheight = $( " # " + id).outerHeight();
var myfatherheight = $( " # " + id).parent().height();
var mytop = (myfatherheight - myheight) / 2 ;
$( " # " + id).css( " position " , " relative " ).css( " top " , mytop + " px " );
}
</ script >
< script type ="text/javascript" >
$(document).ready( function () {
FixIt_Vertically( " div1 " );
});
function FixIt_Vertically(id) {
// var myobj = document.getElementById(id);
var myheight = $( " # " + id).outerHeight();
var myfatherheight = $( " # " + id).parent().height();
var mytop = (myfatherheight - myheight) / 2 ;
$( " # " + id).css( " position " , " relative " ).css( " top " , mytop + " px " );
}
</ script >
IE6,IE8,IE9,chrome, safari, firefox, opera测试全部通过!
欢迎拍砖。