未知宽高元素水平垂直居中
一、vertical-align:middle
<style> *{ margin: 0px; padding: 0px; } .wrap { position: absolute; 100%; height: 100%; text-align: center; background: #92b922; } .test { background: #de3168; display: inline-block; color: #fff; padding: 20px; } .vamb { display: inline-block; 0px; height: 100%; vertical-align: middle; } </style>
<div class="wrap"> <b class="vamb"></b> <div class="test"> 水平垂直居中了吧<br> 两行文字哦 </div> </div>
二、transform
<style> *{ margin:0px; padding:0px; } body{ background: #92b922; } .test { background: #de3168; color: #fff; position: absolute; left:50%; top:50%; -webkit-transform:translate(-50%,-50%); transform:translate(-50%,-50%); } </style>
三、利用弹性盒模型
<style> *{ margin: 0px; padding: 0px; } .flex { display:-webkit-box; display:-ms-flex; display:-webkit-flex; display:flex; } .flex-hc { -webkit-box-pack:center; -ms-justify-content:center; -webkit-justify-content:center; justify-content:center; } .flex-vc { -webkit-box-align:center; -ms-align-items:center; -webkit-align-items:center; align-items:center; } .wrap { position:absolute; 100%; height:100%; left:0px; top:0px; background: #92b922; } .test { background: #de3168; color: #fff; } </style>
<div class="wrap flex flex-hc flex-vc"> <div class="test"> 水平垂直居中了吧<br> 两行文字哦 </div> </div>
四、表格
<style> *{ margin: 0px; padding: 0px; } .wrap { 600px; height: 600px; display: table-cell; vertical-align: middle; text-align: center; background: #92b922; } .test { background: #de3168; display: inline-block; color: #fff; padding: 20px; } </style>
<div class="wrap"> <div class="test"> 水平垂直居中了吧<br> 两行文字哦 </div> </div>