css 水平垂直居中那些事

本文是在参考众大神文章基础上,整理的几个常用方案,另外也掺杂个人的一些猜想,如有不妥,请不吝指出
下面开始正题,为了方便验证+展示,下面的案例我会直接附上个人验证的源码+截图

1.

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
  .container{
    position:relative;
    500px;
    height:500px;
    border:1px solid blue;
   }
  .cnt {
    position: absolute;
    margin:auto;	
    200px;
    height:200px;
    border:1px solid red;
    left:0;
    right:0;
    top:0;
    bottom:0;
    }
</style>
</head>
<body>
<div class="container">
<div class="cnt"></div>
</div>
</body>
</html>
</pre>
<code>
<pre>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
.container{
position:relative;
500px;
height:500px;
border:1px solid blue;
}
.cnt {
position: absolute;
margin:auto;	
200px;
height:200px;
border:1px solid red;
left:0;
right:0;
top:0;
bottom:0;
} </style> </head> <body> <div class="container">       <div class="innerCnt"></div> </div> </body> </html>

  (所有实例运行效果图,均类似右图,下面就不在粘图了(笔者太懒。。。。))

 这个案例主要应用了两个div,container和innerCnt组成,子div设成,固定宽高(非auto即可)、绝对定位(absolute)、top/right/bottom/left都设为0才能实现水平垂直居中的效果:

下面是本人猜测:在绝对定位情况下,如果没有设置坐标值(上右下左的距离),则默认吸附父容器左上角,但同时设置了上右下左的距离为等值的情况下相当于四个人同时朝这四个方向一起在拉绳子,当用相同的力量是达到了一个平衡态,使得容器得以水平垂直居中显示...233我太有才了这都想得出来

2.

 1 <!doctype html>
 2 <html lang="en">
 3 <head>
 4 <meta charset="UTF-8">
 5 <title>Document</title>
 6 <style type="text/css">
 7 .container{
 8     display:table-cell; //以表格形式布局
 9     width: 500px;
10     height: 500px;
11     vertical-align: middle; //垂直居中
12     text-align: center;    //水平居中
13     border: 1px solid #000000;
14 }
15 
16 .innerCnt{
17     display:inline-block;
18     width: 200px;
19     height: 200px;
20     border: 1px solid #FF0000;
21 }
22 </style>
23 </head>
24 <body>
25 <div class="container">
26 <div class="innerCnt"></div>
27 </div>
28 </body>
29 </html>

这个例子主要展示的是table-cell的应用 

table-cell 此元素会作为一个表格单元格显示(类似 <td> 和 <th>)

使得整个区块作为一个单元格,通过vitical-align来控制垂直居中,text-align控制水平居中(需要注意的是子元素应该设置为inline-block来作为行内区块)。

3.

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
.container{
    text-align: center;
    width: 500px;
    height: 500px;
    border:1px solid blue;
}
.empty{
    width:100%;
    height:50%;
    margin-bottom:-100px;  //计算所得; =innerCnt.height/2
}
.innerCnt{
    display: inline-block;
    width: 200px;
    height: 200px;
    border:1px solid red;
}
</style>
</head>
<body>
<div class="container">
    <div class="empty"><!--空的内容--></div>
    <div class="innerCnt">hello</div>
</div>
</body>
</html>

利用一个空div来占位,然后通过margin-bottom来占位使得下方元素上提,实现元素的水平(text-align:center)垂直居中。

原文地址:https://www.cnblogs.com/V-JACK/p/5297552.html