这里所说的元素在屏幕中水平垂直居中,指的是某个元素显示在浏览器或者显示设备的正中间,有点类似于Popup的效果。
jQuery.fn.center = function () {
this.css("position","absolute");
this.css("top", ( $(window).height() - this.height() ) / 2+$(window).scrollTop() + "px");
this.css("left", ( $(window).width() - this.width() ) / 2+$(window).scrollLeft() + "px");
return this;
}
//Use the above function as:
$(element).center();
大家可以在这个代码基础上进行修改,让元素在其父元素中水平垂直居中。或者说在其容器中水平垂直居中。当然这种效果也可以使用CSS来实现:
另外还有一些其他的实现方法
< !-- html -->
<div id="outer">
<div id="middle">
<div id="inner">
any text <br>
<b>any height </b><br>
any content, for example generated from DB <br>
everything is vertically centered <br>
</div>
</div>
</div>
< !-- CSS -->
html{height: 100%;}
body {height: 100%;}
#outer {height: 600px; overflow: visible;width: 100%;position: relative;} /* or without overflow */
#outer[id] {display: table; position: static;}
#middle {position: absolute; top: 50%;} /* for explorer only*/
#middle[id] {display: table-cell; vertical-align: middle; width: 100%;position:static;}
#inner {position: relative; top: -50%} /* for explorer only */
/* optional: #inner[id] {position: static;} */
其实还有其他更好的方法,比如前面几篇文章介绍到的各种方法,每种方法各有自己的利弊,使用时自己考虑。
转载烦请注明出处:http://www.w3cplus.com/codes/center-element-screen-jquery.html