君语贤
时光静好,与君语;细水流年,与君同;繁华落尽,与君老...

前端设计>知识整理>正文

4种盒子/容器垂直水平居中的方案

2019-01-24 12:03 君语贤垂直容器居中方案水平盒子

4种盒子/容器垂直水平居中的方案

1、定位 盒子宽高已知, position: absolute; left: 50%; top: 50%; margin-left:-自身一半宽度; margin-top: -自身一半高度;

2、table-cell布局 父级 display: table-cell; vertical-align: middle;  子级 margin: 0 auto;

3、定位 + transform ; 适用于 子盒子 宽高不定时;

position: relative / absolute;
/*top和left偏移各为50%*/
top: 50%;
left: 50%;
/*translate(-50%,-50%) 偏移自身的宽和高的-50%*/
transform: translate(-50%,-50%); 注意这里启动了3D硬件加速哦 会增加耗电量的 (至于何是3D加速 请看浏览器进程与线程篇)

4、flex 布局

父级:

/*flex 布局*/
display: flex;
/*实现垂直居中*/
align-items: center;
/*实现水平居中*/
justify-content: center;

再加一种水平方向上居中 :margin-left : 50% ; transform: translateX(-50%);

本文链接:https://www.weguiding.com/zhishi/202.html