#demo {
position: absolute;
width: 200px;
height: 200px;
left: 50%;
top: 50%;
margin: -100px 0 0 -100px;
background: #5BBF5A;
}
把元素的定位设为据对定位,left和top设为相对于最近的已定位祖先元素的50%,再把div的上外边距和左外边距设为元素宽和高一半的负值。这种实现方式只能对宽和高固定的div有效。
#demo {
position: absolute;
width: 200px;
height: 200px;
background: #5BBF5A;
}
function makeElementCenter (element){
//页面可视区宽度和高度
var pageWidth = document.documentElement.clientWidth;
var pageHeight = document.documentElement.clientHeight;
//元素的宽和高
var elementWidth = element.offsetWidth;
var elementHeight = element.offsetHeight;
element.style.left = (pageWidth - elementWidth) / 2 + ‘px‘;
element.style.top = (pageHeight - elementHeight) / 2 + ‘px‘;
}
这种方式对不固定宽和高的div也有效
#demo {
position: absolute;
width: 200px;
height: 200px;
background: #5BBF5A;
}
$(".demo").css({
left: ($(window).width() - $(".demo").outerWidth()) / 2,
top: ($(window).height() - $(".demo").outerHeight()) / 2
});
原理和javascript的实现原理一样
原文:http://blog.csdn.net/pigsuper/article/details/44598575