元素水平垂直居中

1.第一种情况,宽度固定,高度auto情况下

js判断,水平居中margin:0 auto;垂直居中用js判断元素相对于浏览器可视区域的高度

<style type="text/css">
*{
padding: 0;
margin: 0;
}
#news{
400px;
border: 4px solid blue;
padding: 30px;
/*margin: 0 auto;*/
}
</style>
<script type="text/javascript" src="jquery-1.7.2.min.js"></script>
<script type="text/javascript">
$(function(){
function juzhong(){
// 获得可视区域高度
var window_height = $(window).height();
// 获得元素本身的高度
var news_height = $('#news').outerHeight();
// 计算margin-top值
var mtop = (window_height - news_height)/2;
// 给box赋值
$('#news').css('margin-top', mtop+'px');
}

juzhong();

// 给浏览器加resize事件
$(window).resize(function() {
juzhong();
});

})

</script>

<body><div id="news"></div></body>

或者:(有父级元素的情况下)

div{

200px; height: 200px; 

margin:auto;

position: absolute;

left: 0; top: 0; right: 0; bottom: 0;

}

2.第二种情况,宽高固定情况下,(加上元素float浮动)

 如果有父元素,则父元素需要相对定位,子元素绝对定位 

div{

width:500px;height:300px;

(float:left;)

position: relative;

left:50%;right:50%;

margin:-150px 0 0 -250px;

}

原文地址:https://www.cnblogs.com/luckyuns/p/5989981.html