CSS盒子水平垂直居中的四种方式

2020-03-23  本文已影响0人  晚月川

一个元素在另一个元素水平垂直居中位置 面试题

需要宽高的两种

第一个方法

.box {
    position: absolute;
    left:50%;
    top:50%;
    margin-left:-50px;
    margin-top:-50px;
    width:100px;
    height: 100px;
    background-color: red;
}

第二种方法

.box {
    position: absolute;
    left:0;
    top:0;
    right:0;
    bottom:0;
    margin:auto;
    width:100px;
    height: 100px;
    background-color: green;
}

不要需要宽高的两种

第一种方法
transforms 变形(最简单的方法)

内容块定义transform: translate(-50%,-50%) 必须加上top: 50%; left: 50%;

.box {
     padding: 20px;
     background: orange;
     color: #fff;
     position: absolute;
     top: 50%;
     left: 50%;
     border-radius: 5px;
     -webkit-transform: translate(-50%, -50%);
     -moz-transform: translate(-50%, -50%);
     transform: translate(-50%, -50%);
}

第二种方法
给父元素加CSS属性

.box{
    justify-content: center; /*子元素水平居中*/
    align-items: center; /*子元素垂直居中*/
    display: -webkit-flex;
}
上一篇 下一篇

猜你喜欢

热点阅读