Home >Web Front-end >HTML Tutorial >Six ways to achieve vertical and horizontal centering in CSS_html/css_WEB-ITnose
is often used in projects. Today I summarized it:
Demo address: http://codepen .io/anon/pen/xGdpOa
The following two classes are public classes for better display, non-core code
.common{ width: 600px;height: 180px; background-color:#56abe4; color: #fff; margin: 15px auto; border-radius: 3px; } .con{ display: inline-block; padding: 15px; width: 160px; height: 80px; background-color: orange; }
Text part:
First Method:
/*position: absolute;top:0;right: 0;bottom: 0;left: 0;margin: auto;*/
HTML structure:
<div class="common block1"> <div class="inner1 con"> position: absolute; top:0;right: 0;bottom: 0;left: 0; margin: auto; </div></div>
CSS part:
.block1{ position: relative; } .inner1{ position: absolute; top:0;right: 0;bottom: 0;left: 0; margin: auto; }
Second method:
/*display : table-cell*/
HTML structure:
<div class="common block2"> <div class="con"> display: table-cell; text-align: center; vertical-align: middle; </div></div>
CSS part:
.block2{ display: table-cell; text-align: center; vertical-align: middle; }
>
/*display: flex;*/
HTML structure:
<div class="common block3"> <div class="con"> display: flex; align-items: center; justify-content: center; </div></div>CSS part:
The fourth method:
.block3{ display: flex; align-items: center; justify-content: center; }
/*Negative positioning*/
HTML structure:
CSS part:
<div class="common block4"> <div class="inner4 con"> position: absolute; top: 50%; left: 50%; 并利用负定位消除元素的上下,左右偏移 </div></div>
Fifth method:
.block4{ position: relative; } .inner4{ position: absolute; top: 50%; left: 50%; margin-top: -55px;/*80/2+15=55*/ margin-left: -95px;/*160/2+15=95*/ }
/*transform*/
HTML structure:
CSS part:
<div class="common block5"> <div class="inner5 con"> position: absolute; top: 50%; left: 50%; transform:translate(-50%,-50%); </div></div>
.block5{ position: relative; } .inner5{ position: absolute; top: 50%; left: 50%; transform:translate(-50%,-50%); word-wrap: break-word; }The sixth method: (better compatibility)
/ *Inline block*/ HTML structure:
CSS part:
<div class="common block6"> <div class="inner6 con">行内块:<br/>谨记span标签与该div之间是没有空白的,否则会产生误差</div><span></span></div>
There are compatibility issues with the above solutions. Please check the browser compatibility of core css before using it. The query address is: http://caniuse.com/
.block6{ text-align:center;} .inner6,.block6 span{ display:inline-block; *display:inline; zoom:1; vertical-align:middle; } .inner6{max-width:100%;max-height:100%;} .block6 span{width:0;height:100%;}
and above.
Additions are welcome~