1、让层水平居中
复制代码代码如下:
.className{
width:270px;
height:150px;
margin:0 auto;
}
使用margin:0 auto;让层水平居中,留意宽度和高度必不可少。
2、让层垂直居中
复制代码代码如下:
.className{
width:270px;
height:150px;
position:absolute;
left:50%;
top:50%;
margin:-75px 0 0 -135px;
}
将层设置为绝对定位,left和top为50%,这时候使用负外边距,负外边距的大小为宽高的一半。
3、在重置窗体的时候层依旧保持居中
复制代码代码如下:
$(document).ready(function(){
$(window).resize(function(){
$(.className).css({
position:absolute,
left: ($(window).width()
- $(.className).outerWidth())/2,
top: ($(window).height()
- $(.className).outerHeight())/2
});
});
$(window).resize();
});
这里用到的jquery的方法。
resize()事件:当在窗体重置大小时触发。
outerWidth():获取第一个匹配元素外部宽度(默认包括补白和边框)。