水平垂直居中div jquery
水平垂直居中div jquery
<html>
<head>
<script src="jquery.js"></script>
<style>
#nw{border:1px solid #000; background:#ccc; height:220px; width:520px;}
</style>
</head><body>
<div id="nw">我是居中的层!</div>
</body>
</html>
<script>
$(function(){$('#nw').css教程({'position':'absolute','left':($(document).width()-520)/2,'top':($(document).height()-220)/2});
});
</script>
方法二十
jquery.fn.center = function(params) {
var options = {
vertical: true,
horizontal: true
}
op = jquery.extend(options, params);
return this.each(function(){var $self = jquery(this);
var width = $self.width();
var height = $self.height();
var paddingtop = parseint($self.css("padding-top"));
var paddingbottom = parseint($self.css("padding-bottom"));
var bordertop = parseint($self.css("border-top-width"));
var borderbottom = parseint($self.css("border-bottom-width"));
var mediaborder = (bordertop+borderbottom)/2;
var mediapadding = (paddingtop+paddingbottom)/2;
var positiontype = $self.parent().css("position");
var halfwidth = (width/2)*(-1);
var halfheight = ((height/2)*(-1))-mediapadding-mediaborder;
var cssprop = {
position: 'absolute'
};if(op.vertical) {
cssprop.height = height;
cssprop.top = '50%';
cssprop.margintop = halfheight;
}
if(op.horizontal) {
cssprop.width = width;
cssprop.left = '50%';
cssprop.marginleft = halfwidth;
}
if(positiontype == 'static') {
$self.parent().css("position","relative");
}
$self.css(cssprop);
});};
方法三
$("element").center(); //vertical and horizontal
$("element").center({ horizontal: false // only vertical });
插件下载:jquery.include.js.txt(下完自己改后缀名)
总结
jquery为我们提供了方便简单的控制方法,比如设置一个水平垂直居中的层,我们可以使用$(document).width()和$(document).height()来获取窗口的宽度和高度,接下来进行一个简单的计算即可让层水平垂直居中。
补充:网页制作,jquery