This layout is often used in front-end layout, horizontal and vertical center; also often ask to interview.
A. To achieve absolute positioning center
Note: use absolute positioning layout when the outer element must also be provided with a position attribute specific settings to see why the value of the specific situation. As long as static on the line.
1. achieved by positioning + margin
The four offset direction is 0, then margin: auto for centered.
. 1 .center { 2 / * div basic attributes * / . 3 height : 500px ; . 4 width : 500px ; . 5 background-Color : Blue ; . 6 / * absolute positioning * / . 7 position : Absolute ; . 8 / * the positioning achieved + margin dual center * / . 9 Top : 0 ; 10 left : 0 ; . 11 bottom : 0 ; 12 right: 0; 13 margin:auto; 14 }
2. achieved by positioning + transform
Set top and left offset 50% at this time is the middle position of the start of div, the div is left corner, so it needs a leftward direction by 50% of the width (height).
.center { / * basic properties of div * / height : 500px ; width : 500px ; background-Color : Blue ; / * absolute positioning * / position : Absolute ; / * By centrally positioning transform dual + * / Top : 50% ; left : 50% ; -ms-Transform : Translate (-50%, -50%) ; -moz-Transform : Translate (-50%, -50%) ; -o-transform: translate(-50%, -50%); transform: translate(-50%, -50%); }
3. + margin achieved by positioning ( this method must know the length and width centered div )
This method is similar to the second, by providing the top, left offset, then the margin-top, margin-left set value is 50% of the width (height) as the correction.
. 1 .center { 2 / * div basic attributes * / . 3 height : 500px ; . 4 width : 500px ; . 5 background-Color : Blue ; . 6 / * absolute positioning * / . 7 position : Absolute ; . 8 / * the positioning achieved + margin dual center * / . 9 Top : 50% ; 10 left : 50% ; . 11 margin-Top : -250px; 12 margin-left: -250px; 13 }
II. Achieved through flex centered layout
1. layout flex element becomes the parent, and then set the align-items can justify-content property
. 1 .father { 2 / * basic properties of the parent element * / . 3 height : 1000px ; . 4 width : 1000px ; . 5 border : 1px Solid Red ; . 6 / * set flex layout * / . 7 the display : flex ; . 8 / * set flex attribute * / . 9 align = left-items : Center ; 10 The justify-Content : Center ; . 11 } 12 is .center { 13 is / * basic properties of div * / 14 height : 500px ; 15 width : 500px ; 16 background-Color : Blue ; . 17 }