CSS垂直居中

时间:2022-07-22
本文章向大家介绍CSS垂直居中,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

方案1

关键代码

父类:

display: table-cell;

vertical-align: middle;

示例:

    <style>
        .parent {
            width: 200px;
            height: 600px;
            background-color: blueviolet;
            display: table-cell;
            vertical-align: middle;
        }

        .son {
            width: 200px;
            height: 200px;
            background-color: cornflowerblue;
        }
    </style>
</head>
<body>
    <div class="parent">
        <div class="son">哈哈</div>
    </div>
</body>

扩展知识

vertical-align属性:用于设置文本内容的垂直方向对齐方式

top:顶部对齐

middle:居中对齐

bottom:底部对齐

优缺点分析

  • 优点: 浏览器兼容性比较好
  • 缺点: vertical-algin属性具有继承性,导致父级元素的文本也是居中显示的

方案2

关键代码

父类:position: relative;

子类:

top: 50%;

transform: translateY(-50%);

示例:

    <style>       
        .parent {
            width: 200px;
            height: 600px;
            background-color: blueviolet;
            position: relative;
        }

        .son {
            width: 200px;
            height: 200px;
            background-color: cornflowerblue;
            position: absolute;
            top: 50%;
            transform: translateY(-50%);
        }
    </style>
</head>
<body>
    <div class="parent">
        <div class="son">哈哈</div>
    </div>
</body>

优缺点分析

  • 优点:父级元素是否脱离文档流,不影响子级元素垂直居中效果
  • 缺点:transform属性是CSS3新属性,浏览器支持情况不好

方案3

关键代码

父类:position: relative;

子类:

position: absolute;

top: 0;

bottom: 0;

margin: auto 0;

示例

    <style>
        .parent {
            width: 200px;
            height: 600px;
            background-color: blueviolet;
            position: relative;
        }

        .son {
            width: 200px;
            height: 200px;
            background-color: cornflowerblue;
            position: absolute; 
            top: 0; 
            bottom: 0; 
            margin: auto 0;
        }
    </style>
</head>
<body>
    <div class="parent">
        <div class="son">哈哈</div>
    </div>
</body>