CSS制作水平垂直居中对齐 多种方式各有千秋

2020-05-16 07:00:21易采站长站整理

Html Markup


<div class=”container”>
<p>Centered In The Middle Of The Page With jQuery</p>
</div>

CSS Code


.container{
background-color:#338BC7;
width:270px;
height:150px;
}

jQuery Code


$(document).ready(function(){
$(window).resize(function(){
$(‘.container’).css({
position:’absolute’,
left: ($(window).width() – $(‘.container’).outerWidth())/2,
top: ($(window).height() – $(‘.container’).outerHeight())/2
});
});
// 最初运行函数
$(window).resize();
});

优点:

这种方法,结构简单,易懂,不需要固定元素的大小。兼容各浏览器。

缺点:

需要调用jQuery,如果不支持js或者用户禁掉了js,那么将无法正常运行,那就是杯具了。

上面这种方法对实现页面居中布局很方便,下面我根据上面的思路和方法二写了一个实现元素水平垂直居中的小插件

jQuery Plugin


(function($){
$.fn.vhAlign = function(){
return this.each(function(i){
//获取元素的内容高度
var h = Math.ceil($(this).height());
//outerHeight=padding+border+height
var oh = Math.ceil($(this).outerHeight());
//取得margin-top值
var mt = Math.ceil(oh / 2);
//取得元素宽度
var w = Math.ceil($(this).width());
//outerWidth=padding+border+width
var ow = Math.ceil($(this).outerWidth());
//取得margin-left
var ml = Math.ceil(ow / 2);
//实现元素居中效果
$(this).css({
“margin-top”: “-” + mt + “px”,
“top”: “50%”,
“margin-left”: “-” + ml + “px”,
“left”: “50%”,
“width”:w,
“height”:h,
“position”: “absolute”
});
});
};
})(jQuery);

Html Markup


<div class=”wrap”>
<p>test jquery</p>
</div>

接下来需要调用刚才写好的jQuery插件


<script type=”text/javascript” src=”vhAlign.js”></script>

最后需要在div.wrap调用这个function


<script type=”text/javascript”>
$(document).ready(function(){
$(“.wrap”).vhAlign();
});
</script>

这里有一点需要特别注意,如果元素不是相对于body居中,那么需要在其父元素中进行相对定位。

上面我们一起见证了八种不同方法实现元素的垂直居中效果,下面我们在简单的看一下如何实现元素的水平居中(其实上面有一些效果也实现了水平居中,你可以慢慢回想一下)。

方法一: