让一个不定宽高的盒子垂直水平居中

1,446 阅读1分钟
  • 方法一:定位+css3
html,body{
    width: 100%;
    height: 100%;
}
body{
    position: relative;
    background-color: blue;
}
.box{
    background-color: pink;
    font-size: 36px;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%,-50%);
}

<html>
    <body>
        <div class="box">123</div>
    </body>
</html>

  • 方法二:css
.outer {
    width: 300px;
    height: 300px;
    background-color: gray;
    display: table-cell;
    text-align: center;
    vertical-align: middle;
}
.inner {
    vertical-align: middle;
    display: inline-block;
    background-color: skyblue;
}

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

  • 方法三:flex布局
.outer {
    width: 300px;
    height: 300px;
    background-color: gray;
    display: flex;
    justify-content: center;
    align-items:center;
}

.inner {
    background-color: skyblue;
}

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