css垂直居中7种常用方法

image.png
image.png

居中元素宽高已知

1. absolute + margin auto

 .parent {
            position: relative;
            width: 100px;
            height: 100px;
            border: 3px solid steelblue;
            margin: 0 auto;
        }
.child1 {
            background: tomato;
            width: 50px;
            height: 50px;
            /**关键代码**/
            position: absolute;
            top: 0;
            bottom: 0;
            left: 0;
            right: 0;
            margin: auto;
        }

2.absolute + 负margin

.parent {
            position: relative;
            width: 100px;
            height: 100px;
            border: 3px solid steelblue;
            margin: 0 auto;
        }
.child2 {
           background: tomato;
            width: 50px;
            height: 50px;
            position: absolute;
            top: 50%;
            left: 50%;
            margin-top: -25px; /**宽度的一半**/
            margin-left: -25px;
        }

3.absolute + calc

.parent {
            position: relative;
            width: 100px;
            height: 100px;
            border: 3px solid steelblue;
            margin: 0 auto;
        }
.child3 {
           background: tomato;
            width: 50px;
            height: 50px;
            position: absolute;
            top: calc(50% - 25px);
            left: calc(50% - 25px);
        }

居中元素宽高未知

4.absolute + transform

.parent {
            position: relative;
            width: 100px;
            height: 100px;
            border: 3px solid steelblue;
            margin: 0 auto;
        }
.child4 {
           background: tomato;
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
        }

5.line-height + vertical-align

 .parent5 {
            width: 100px;
            border: 3px solid steelblue;
            margin: 0 auto;
            /**关键代码**/
            line-height: 100px;
            text-align: center;
        }
 .child5 {
            background: tomato;
            /**关键代码**/
            display: inline-block;
            vertical-align: middle;
            line-height: initial;
        }

6.flex布局

.parent6 {
            width: 100px;
            height: 100px;
            border: 3px solid steelblue;
            margin: 0 auto;
            /**关键代码**/
            display: flex;
            justify-content: center;
            align-items: center;
        }

7.flex + margin auto

.parent7 {
            width: 100px;
            height: 100px;
            border: 3px solid steelblue;
            /**关键代码**/
            display: flex;
            margin: 0 auto;
        }
.child7 {
            margin: auto;
        }
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容