1.水平居中
.div{ margin:0 auto; (或者 margin:auto;) width:500px; height:300px; }
2.使用margin水平垂直居中
方式一:
.div { text-align: center; line-height: 200px; border: 2px pink solid; width: 300px; height: 200px; position: absolute; left: 50%; top: 50%; margin: -100px 0 0 -150px;}
方式二:
块级元素水平,垂直居中
3.jquery实现DIV水平垂直居中
.div { text-align: center; line-height: 200px; border: 2px pink solid; width: 300px; height: 200px; }
< script >$(window).resize(function(){ $(".div").css({ position: "absolute", left: ($(window).width() - $(".div").outerWidth())/2, top: ($(window).height() - $(".div").outerHeight())/2 }); }); $(function(){ $(window).resize(); }); < /script >
4.使用css3 tansform属性
块级元素水平,垂直居中 adfagagafajkfhla
效果如下:
单独设置垂直居中可使用:
top:50%;tansfrom:translateY(-50%);
单独使用水平居中可使用:
left:50%;tramsform:translateX(-50%);
5.table-cell
注意:可能会破坏页面整体布局
块级元素水平,垂直居中 adfagagafajkfhla
效果如下:
6.使用示例:DIV创建水平垂直居中遮罩层
Div层居中
效果: