css中实现水平,垂直居中的5种方法

  • 方法一:行高法
  • 方法二:内边距法
  • 方法三:CSS3的box方法
  • 方法四: 绝对定位法
  • 方法五:模拟表格法
DIV中的元素水平垂直居中#wrap{width:990px; height:400px; background:#CCCCCC; } #wrap{position:absolute; left:50%; top:50%; margin-left:-495px; margin-top:-200px} #wrap2{width:200px; margin:0 auto; padding-top:35px; }/*方法一:行高法*/ #box{ width:200px; height:50px; background: #FFCC00; margin-bottom:20px; position:relative; font-size:16px; } .box1{line-height:50px; text-align:center; }/*方法二:内边距法*/ .box2{width:200px; font-size:16px; background:#FFCC00; margin:20px 0; } .box2{text-align:center; padding:16px 0px; }/*方法三:CSS3的box方法*/ .box3{ justify-content:center; align-items:center; display: -webkit-box; -webkit-box-orient: horizontal; -webkit-box-pack: center; -webkit-box-align: center; display: -moz-box; -moz-box-orient: horizontal; -moz-box-pack: center; -moz-box-align: center; display: -o-box; -o-box-orient: horizontal; -o-box-pack: center; -o-box-align: center; display: -ms-box; -ms-box-orient: horizontal; -ms-box-pack: center; -ms-box-align: center; display: box; box-orient: horizontal; box-pack: center; box-align: center; }/*方法四:绝对定位法*/ .div4{position: absolute; left: 50%; top:50%; display:block; margin-top:-8px; margin-left:-40px; }/*方法五: 模拟表格法*/ .div5{display:table; } .div5a{display:table-cell; vertical-align:middle; text-align:center; }行高法居中 内边距法居中 CSS3中的box法 绝对定位法 模拟表格

    推荐阅读