Six methods for vertical and horizontal center using Css
It is often used in projects. today we summarize:
Demo address: http://codepen.io/anon/pen/xGdpOa
The following two classes are public classes for better display and 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;}
Body part:
Method 1:
/* Position: absolute; top: 0; right: 0; bottom: 0; left: 0; margin: auto ;*/
HTML structure:
position: absolute;top:0;right: 0;bottom: 0;left: 0;margin: auto;
CSS section:
.block1{position: relative;}.inner1{position: absolute;top:0;right: 0;bottom: 0;left: 0;margin: auto;}
Method 2:
/* Display: table-cell */
HTML structure:
display: table-cell;text-align: center;vertical-align: middle;
CSS section:
.block2{display: table-cell;text-align: center;vertical-align: middle;}
Method 3:
/* Display: flex ;*/
HTML structure:
display: flex; align-items: center; justify-content: center;
CSS section:
.block3{display: flex;align-items: center;justify-content: center;}
Method 4:
/* Negative positioning */
HTML structure:
Position: absolute; top: 50%; left: 50%; and the negative position is used to eliminate the vertical and vertical offsets of elements.
CSS section:
.block4{ position: relative;}.inner4{position: absolute;top: 50%;left: 50%;margin-top: -55px;/*80/2+15=55*/ margin-left: -95px;/*160/2+15=95*/}
Method 5:
/* Transform */
HTML structure:
position: absolute;top: 50%;left: 50%; transform:translate(-50%,-50%);
CSS section:
.block5{ position: relative;}.inner5{position: absolute;top: 50%;left: 50%; transform:translate(-50%,-50%); word-wrap: break-word;}
Method 6: (good compatibility)
/* Intra-Row block */
HTML structure:
Intra-Row block:
Remember that there is no blank between the span tag and the p; otherwise, an error will occur.
CSS section:
.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%;}
The above solutions have compatibility problems, please first query the core css browser compatibility, query address: http://caniuse.com/
Above.
Welcome to add ~