Here to tell us about the most common end centered way web pages
The basic structure of the page: a simple div
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <style> :root , html{ height: 100%; width: 100%; } div{ width: 100px; height: 100px; background: red; } </style> </head> <body> <div class="mid"></div> </body> </html> </html>
1. Using position
:root , html{ height: 100%; width: 100%; } div{ width: 100px; height: 100px; background: red; } .Mid { position : Absolute ; Top : 50% ; left : 50% ; / * through the top 50% and 50% left to make a left vertex centered div * / }
Several make div own translation half way
1. For the known width and height
By their own half of the size of the margin translation
.mid{ position: absolute; top: 50%; left: 50%; margin-left: -50px; margin-top:-50px; }
Calc function is calculated by
.mid{ position: absolute; top:calc(50% - 50px); left:calc(50% - 50px); }
By transform the translate
.mid{ position: absolute; top:50%; left:50%; transform: translate(-50%,-50%); }
2. The use of an elastic flex box model
body{ width: 100%; height:100%; display: flex; align-items:center; justify-content: center; }
3. Using margin: auto position plus four directions of 0
Four direction is set to 0, with
.mid{ position: absolute; margin:auto; left: 0; top: 0; bottom:0; right: 0; }
4.利用table table-cell
You can use table-cell Vertical-align = left : Middle Vertical Centering
Then its children in the center can be used to achieve vertical margin
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <style> :root, html { height: 100%; width: 100%; } body { width: 100%; height: 100%; display: table; } .wrapper { width: 100%; height: 100%; display: table-cell; vertical-align: middle; } .mid { margin:0 auto; width: 100px; height: 100px; background: red; } </style> </head> <body> <div class="wrapper"> <div class="mid"> </div> </div> </body> </html>
Let vertically centered within the horizontal text block element
<div class="mid">123</div>
.mid{ width: 100px; height: 100px; text-align: center; line-height: 100px; background: red; }
Centered manner on vertical and horizontal share here. Individual vertical or horizontal center as long as the same principles can be separated by
These are commonly centered manner, is the most frequently used model margin cartridge and cassette to flex the resilient centering
Also recommend the use of these two methods.
If you have any questions please discuss with the exchange, the follow-up if there is any other way will replenish center.