垂直居中的几种方法

方法一

这个方法把div 的显示方式设置为表格,因此我们可以使用表格的 vertical-align属性。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>垂直居中</title>
    <style type="text/css">
        #wrapper {
            display: table;    /*here*/
            background:blue;
            width:400px;
            height:200px;
        }
        
        #container {
            display: table-cell;       /*here*/       
            vertical-align: middle;    /*here*/
            background: yellow;
            width:300px;
            height:50%;
        }
    </style>
</head>

<body>
    <div id="wrapper">
        <div id="container">
            我要用表格属性垂直居中,
            我要用表格属性垂直居中,
            我要用表格属性垂直居中,
            我要用表格属性垂直居中
        </div> 
    </div> 
</body>
</html>

实现如图:

优点:

  • container 可以动态改变高度(不需在 CSS 中定义)。当 wrapper 里没有足够空间时, container 不会被截断
  • 例如
  •  #wrapper {
                display: table;    /*here*/
                background:blue;
                width:100px;
                height:100px;
            }
            
            #container {
                display: table-cell;       /*here*/       
                vertical-align: middle;     /*here*/
                background: yellow;
                width:50%;
                height:50%;
            }

    效果如图:

缺点:

  • Internet Explorer(甚至 IE8 )中无效,许多嵌套标签(其实还好)。
方法二

猜你喜欢

转载自www.cnblogs.com/sunmarvell/p/9123698.html