让div盒子相对父盒子垂直居中的几种方法

方法1:宽度和高度已知的。 
思路: 
给父元素相对定位 
给子元素绝对定位 
left: 50%;top: 50%; 
margin-left: 负的宽度一半。 
margin-top: 负的高度一半;
<html> 2 <head lang="en"> 3 <meta charset="UTF-8"> 4 <title></title> 5 </head> 6 <style> 7 8 #one{ 9 400px; 10 height: 400px; 11 border: 1px solid #000; 12 position: relative; 13 } 14 #two{ 15 200px; 16 height: 200px; 17 background-color: red; 18 position: absolute; 19 top: 50%; 20 left: 50%; 21 margin-left: -100px; 22 margin-top: -100px; 23 24 } 25 </style> 26 <body> 27 <div id="one"> 28 <div id="two"></div> 29 </div> 30 </body> 31 </html>
方法2:宽度和高度自己未知 
意思就是说子盒子本身还是有宽度和高度的,只是自己未知。 
思路: 
给父盒子相对定位 
给子盒子绝对定位 
top、right、bottom、left全为0 
margin: auto;
<html> 2 <head lang="en"> 3 <meta charset="UTF-8"> 4 <title></title> 5 </head> 6 <style> 7 #one{ 8 400px; 9 height: 400px; 10 border: 1px solid #000; 11 position: relative; 12 } 13 14 #two{ 15 200px; 16 height: 200px; 17 background-color: red; 18 position: absolute; 19 margin: auto; 20 top: 0; 21 left: 0; 22 right: 0; 23 bottom: 0; 24 } 25 img { 26 display:table-cell; 27 text-align:center; 28 vertical-align:middle; 29 } 30 </style> 31 <body> 32 <div id="one"> 33 <div id="two"></div> 34 <img src="" alt=""/> 35 </div> 36 </body> 37 </html>
css3实现
.element {
     600px; height: 400px;
    position: absolute; left: 50%; top: 50%;
    transform: translate(-50%, -50%);    /* 50%为自身尺寸的一半 */
  }

方法3:flex布局

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>垂直居中</title>
    <style type="text/css">
        .box{
             400px;
            height: 200px;
            background: #f99;
        }
        .box1{
             200px;
            height: 100px;
            background: green;
        }
        .center{
            display: flex;
            justify-content: center;
            align-items: center;
        }
    </style>
</head>
<body>
    <div class="box center">
        <div class="box1">

        </div>
    </div>
</body>
</html>

 那么,问题来了,如何垂直居中一个<img>?

//<img>的容器设置如下
        #container {
            display: table-cell;
            text-align: center;
            vertical-align: middle;
        }
原文地址:https://www.cnblogs.com/zhaosijia----1234/p/8886262.html