查了很多很多,想法都是好的,想只用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>

IE6,IE8,IE9,chrome, safari, firefox, opera测试全部通过!

欢迎拍砖。

相关文章:

  • 2021-06-05
  • 2021-10-29
  • 2021-06-24
  • 2022-12-23
  • 2022-12-23
  • 2021-10-09
猜你喜欢
  • 2021-12-14
  • 2022-01-08
  • 2021-07-04
  • 2021-12-31
  • 2021-04-30
  • 2022-01-25
  • 2021-10-13
相关资源
相似解决方案