One: Horizontal centering
1. Allow child to be centered horizontally in parent, as shown below
<!DOCTYPE HTML><HTML><HeadLang= "en"> <MetaCharSet= "UTF-8"> <title></title> <style>. Parent{width:300px;Height:200px;Border:1px solid #000;text-align:Center; }. Child{width:50px;Height:50px;Border:1px solid Red;Display:Inline-block;} </style></Head><Body><Divclass= "Parent"> <Divclass= "Child"></Div></Div></Body></HTML>
The first method: Add the Text-align:center attribute to the parent element, the handle element into the inline box, Display:inline-block (the child element can be an inline element or a block-level element )
The second method: add margin:0 Auto to child element, attribute ( child element must have width, and must be block level element );
The third method: use absolute positioning and relative positioning to achieve
. parent{ width:300px; height:200px; border:1px solid #000; position:relative;//set relative positioning to match the absolute positioning of child elements } . child{ width:50px; height:50px; border:1px solid red; Position:absolute; left:50%; Margin-left: Half of the width of the -25px;//element }
Two, vertical center
The first method: use absolute positioning as above
. parent{ width:300px; height:200px; border:1px solid #000; position:relative;//set relative positioning to match the absolute positioning of child elements } . child{ width:50px; height:50px; border:1px solid red; Position:absolute; top:50%; Margin-top: -25px;
The second method:
Add to Parent
Display:table-cell;
Vertical-align:middle;
CSS and HTML layout tips