css3实现垂直水平居中

html代码:

<div class="outer">
    <div class="inner"></div>
</div>

方法一:flex布局

.outer{
    display: flex;
    justify-content: center; //水平居中
    align-items: center //垂直居中
}

方法二: position + transform, inner宽高未知

.outer{
    position:relative;
}
.inner{
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%,-50%);
}

left: 50%;top: 50%;这里的百分比是父元素outer的width和hight的百分之五十,基点是outer的左上角,移动的是inner的中心。这行代码作用便是inner的中心相对以outer左上角为原点,向x,y正轴移动百分之50的距离。

transform: translate(-50%,-50%);这里的百分之50是相对于inner的宽和高来说的,基点是outer的左上角。作用便是inner中心相对outer左上角为原点,向x,y正轴移动负百分之50的距离,即左移上移。

方法三:position + 负margin, inner宽高已知

.outer{
   position: relative;
  width:200px;
  height:200px } .inner{ 100px; height: 100px; position: absolute; left: 50%; top: 50%; margin-left: -50px; margin-top: -50px; }

margin为负数效果是使元素中心相对父元素左上角左移和上移。但inline元素有可能会导致margin不生效的情况,具体可参考:https://www.cnblogs.com/xiaohuochai/p/5314289.html

方法四:设置各个方向的距离都是0,再将margin设为auto,也可以实现,前提是inner宽高已知

.outer {
   position: relative;
  
200px;
  height: 200px;
}
.inner {
     100px;
    height: 100px;
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    margin: auto;  //上面4行光使用margin:0 auto 无效;top指的是顶部边缘,margin-top是顶部外边距,两者不等价
}

方法五:absolute + calc

.outer {
    position: relative;
    background-color: green;
     200px;
    height: 200px;
}
.inner {
    position: absolute;;
     100px;
    height: 100px;
    top: calc(50% - 50px); 
     //50px的意义是inner高的一半,百分之五十作用等同top:50%
    left: calc(50% - 50px);
    background-color: yellow
}                    

方法六:grid(据说浏览器兼容性不是很好,不推荐使用)

.outer {
    background-color: green;
     200px;
    height: 200px;
    display: grid;
}
.inner {
     50px;
    height: 50px;
    align-self: center;  //垂直居中
    justify-self: center;  //水平居中
    background-color: yellow
}

更多方法可以参考:https://segmentfault.com/a/1190000016389031

原文地址:https://www.cnblogs.com/AwenJS/p/12714129.html