html的元素水平垂直居中应该怎么设置

如题所述


这次给大家带来html的元素水平垂直居中应该怎么设置,设置html的元素水平垂直居中的注意事项有哪些,下面就是实战案例,一起来看一下。
我们在设计页面的时候,经常要把DIV居中显示,而且是相对页面窗口水平和垂直方向居中显示,如让登录窗口居中显示。
到现在为止,探讨了很多种方法。
HTML:
<body>
<div class="maxbox">
<div class="minbox align-center"></div>
</div>
</body>第一种: CSS绝对定位
主要利用绝对定位,再用margin调整到中间位置。
父元素:
.maxbox{
position: relative;
width: 500px;
height: 500px;
margin: 5px;
box-shadow: 1px 1px 1px rgba(0, 0, 0, 0.8), -1px -1px 1px rgba(0, 0, 0, 0.8);
} 子元素:
.minbox{
width: 200px;
height: 200px;
box-shadow: 1px 1px 1px rgba(0, 0, 0, 0.8), -1px -1px 1px rgba(0, 0, 0, 0.8);
}水平垂直居中对齐:
.align-center{
position: absolute;
left: 50%;
top: 50%;
margin-left: -100px; /*width/-2*/
margin-top: -100px; /*height/-2*/
}第二种: CSS绝对定位 + Javascript/JQuery
主要利用绝对定位,再用Javascript/JQuery调整到中间位置。相比第一种方法,此方法提高了class的灵活性。
父元素:
.maxbox{
position: relative;
width: 500px;
height: 500px;
margin: 5px;
box-shadow: 1px 1px 1px rgba(0, 0, 0, 0.8), -1px -1px 1px rgba(0, 0, 0, 0.8);
} 子元素:
.minbox{
width: 200px;
height: 200px;
box-shadow: 1px 1px 1px rgba(0, 0, 0, 0.8), -1px -1px 1px rgba(0, 0, 0, 0.8);
}水平垂直居中对齐:
.align-center{
position: absolute;
left: 50%;
top: 50%;
} JQuery:
$(function(){
$(".align-center").css(
{
"margin-left": ($(".align-center").width()/-2),
"margin-top": ($(".align-center").height()/-2)
}
);
});几种方法的比较:
第一种CSS绝对定位margin调整,兼容性很好但是欠缺灵活性。如果有很多box里需要水平垂直居中,因其width,height不同而需要写不同的 .align-center 。
第二种使用脚本语言,兼容性很好且弥补了第一种的缺点。不因width,height的改变而影响水平垂直居中的效果。
第三种使用CSS3的一些新的属性,兼容IE10, Chrome, Firefox, 和 Opera。兼容性不太很好,不因width,height的改变而影响水平垂直居中的效果。
相信看了这些案例你已经掌握了方法,更多精彩请关注Gxl网其它相关文章!
相关阅读:
怎样用HTML和CSS做出大白

XHTML中有哪些常用的标签

在HTML/XHTML中的img图像标签应该如何使用
温馨提示:答案为网友推荐,仅供参考
相似回答