This article mainly and everyone introduced the CSS Horizontal Vertical Center solution (6 kinds) of the relevant information, small series feel very good, and now share to everyone, but also for everyone to do a reference. Follow the small series together to see it, hope to help everyone.
Get ready
Creating elements
<p class= "Parent" > <p class= "Child" >child</p></p>
Vertical horizontal centering Scheme one: Absolute+margin negative values when the width is known
. parent { width:400px; height:400px; background:red; Position:relative;}. Child { Position:absolute; left:50%; top:50%; Background:yellow; width:50px; height:50px; margin-left:-25px; margin-top:-25px;}
Vertical horizontal Centering Scheme II: Do not know the case of wide height absolute+transform
. parent { width:400px; height:400px; background:red; Position:relative;}. Child { Position:absolute; left:50%; top:50%; Transform:translate ( -50%,-50%);}
Vertical centering Scheme three: Position+margin:auto
. parent { position:relative; width:200px; height:200px; background:red;}. Child { width:80px; height:40px; Background:yellow; Position:absolute; left:0; top:0; right:0; bottom:0; Margin:auto;}
Vertical centering Scheme four: + Vertical center of multiline text: Table-cell+vertical-align:middle;
. parent { height:300px; width:400px; border:1px solid red; Display:table-cell; Vertical-align:middle; Text-align:center;}. Child { display:inline-block; width:50px; height:50px; Background:blue;} /* or */.parent { width:400px; height:300px; Display:table-cell; Vertical-align:middle; border:1px solid red; Text-align:center;}. Child { display:inline-block; Vertical-align:middle; Background:blue;}
Vertical centering Scheme V: Display:flex
. parent { width:400px; height:200px; background:red; Display:flex; Justify-content:center; Align-items:center;}. Child { height:100px; width:100px; Background:green;}
Vertical centering Scheme VI: pseudo element
. parent { width:200px; height:200px; background:red; Text-align:center;}. Child { height:100px; width:100px; Background:yellow; Display:inline-block; Vertical-align:middle;}. Parent:before { content: ""; height:100%; Vertical-align:middle; Display:inline-block;}