多次坠坑之-垂直水平居中 :)

2018-09-10  本文已影响0人  你滴止痛药儿

由于本人记性太差,多次在这个地方摔倒,今天打算爬起来 :)

实现垂直水平居中的方法总结了三种

第一种、 适用于容器定宽高的场景
div{
    height: 200px;
    width: 200px;
    background-color: pink;
    position: absolute;
    top: 50%;
    left: 50%;
    margin: -100px 0 0 -100px;  
}

因为要设定margin为负数,减去半个宽高,所以不完美。
优化:

div{
    height: 200px;
    width: 200px;
    background-color: pink;
    position: absolute;
    top: 0;
    left:0;
    bottom: 0;
    right: 0;
    margin:auto;
}

适用于块级元素,行级元素

第二种、 未知容器的宽高,利用 transform 属性
div{
    position: absolute;     /* 相对定位或绝对定位均可 */
    width:200px; 
    height:200px;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    background-color: pink;     /* 方便看效果 */
}
第三种、 利用 flex布局,实际使用时应考虑兼容性
.container {
    display: flex; 
    align-items: center;        /* 垂直居中 */
    justify-content: center;    /* 水平居中 */

}
.container div {
    width: 100px;
    height: 100px;
    background-color: pink;     /* 方便看效果 */
} 

flex布局未完待续。。。

上一篇 下一篇

猜你喜欢

热点阅读