Three ways to achieve the centering of child elements in parent elements (collector’s edition)

The three methods are relatively easy to understand. The properties of the parent element are all the same. After the parent element is set, the child element is positioned and then finely adjusted, but the final result is the same, achieving the purpose of centering.

  1. When the width and height of the child element is smaller than that of the parent element, use the positioning method to center

< 
style > Father element { 
width : 400px ; 
height : 400px ; 
border : 1px solid # 
000 ; margin  100px auto 
0 ; position : relative 
; margin : auto; top : 50%; left : 50%; right : 50%; bottom : 50 % ;

  1. Known child element width and height

parent { 
width: 400 px; 
height: 400 px; 
border: 1 px  solid  #000; 
margin  100 px  auto  0 ; 
position: relative; 
} 
child { 
width: 200 px; 
height: 100 px; 
background: yellow; 
position : absolute; 
margin: auto; 
top: 50 %; 
left: 50 %; 
margin-top: -50 px;/*return to half the height*/ 
margin-left: -100 px;/*return to half the width*/ 
}

  1. After fixed positioning, use transform offset to center (css3 technology, IE does not support)
    parent element {

width:400px;
height:400px;
border:1px solid #000;
margin 100px auto 0;
position:relative;
}
child element {
width : 200px ;
 height : 100px ;
 background :yellow;
 position :absolute;
 margin :auto;
 top : 50% ;
 left : 50% ;
 transform : translate (-50%,-50%)
 ; return half the width */ 
}

Leave a Comment

Your email address will not be published. Required fields are marked *