div bottom div horizontally and vertically centered

Other places on the Internet have already described different ways to implement it. Today I will mainly make a detailed summary, I hope it will be helpful to everyone.

ps: I was asked this question during the interview, and I answered it wrong, Lan Shou.

 

Suppose the class name of the parent div is father and the class name of the child div is son. The form in html is as follows:

<div class="father">

       <div class="son">

  </div>

Next, there are four main ways to set the Son center with CSS.

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  1. Method one (using absolute layout): 
    .father{  
    width:500px;  
    height:500px;  
    position:relative;  
    background-color:red;  
    }  
    .son{  
    width:200px;  
    height:200px;  
    position:absolute;  
    top:50%;  
    left:50%;  
    margin-top:-100px;  
    margin-left:-100px;  
    background-color:black;  
    }The  
    renderings are as follows: 
  2. Method two (using table-cell format) 
    .father{  
    width:500px;  
    height:500px;  
    display:table-cell;  
    text-align:center;  
    vertical-align:middle;  
    background-color:red;  
    }  
    .son{  
    width: 200px;  
    height:200px;  
    display:inline-block;  ps: This sentence must be added, otherwise there will be no effect  . Background
    -color:black;  
    }The  
    effect is as above 
    3. Method three (using flexible layout flex) 
    .father{  
    width:500px ;  
    height:500px;  
    display:flex;  
    justify-content:center;  content is centered horizontally 
    align-items:center;  content is centered vertically 
    background-color:red;  
    }  
    .son{  
    width:200px;  
    height:200px;  
    background-color:black ; 
    }The  
    effect is as above 
    4. Method 4 (using absolute layout) 
    .father{  
    width:500px;  
    height:500px;  
    display:relative;  
    background-color:red;  
    }  
    .son{  
    width:200px;  
    height:200px;  
    position:absolute;  
    top :0;  
    right:0;  
    bottom:0;  
    left:0;  
    margin:auto;  
    background-color:black;  
    }The  
    effect is as above

These are the 4 methods I know so far. Both IE and Chrome are compatible. Other browsers are not tested. Visually, they are all compatible. Everyone is welcome to check the missing parts!

Method 3 is easy to use

Guess you like

Origin blog.csdn.net/weixin_41653910/article/details/84860075