实现垂直居中的几种方法整理

82 阅读1分钟

html

<body>
    <div class="container">
      <div class="box">AAAA</div>
    </div>
  </body>

1.子元素有宽高,并且知道宽高多少的情况下

.container {
    position: relative;
    width: 300px;
    height: 300px;
    background-color: crimson;
}

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

2. top left 50%,transform:translate(-50%, -50%)

.container {
    position: relative;
    width: 200px;
    height: 200px;
    background-color: crimson;
 }
.box {
    width: 50px;
    height: 50px;
    background-color: cornflowerblue;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}

3. CSS

.container {
    position: relative;
    width: 200px;
    height: 200px;
    background-color: crimson;
}
.box {
    width: 50px;
    height: 50px;
    background-color: cornflowerblue;
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    margin: auto;
}

4. Flex弹性布局

.container {
    width: 300px;
    height: 300px;
    background-color: cornflowerblue;
    display: flex;
    justify-content: center;
    align-items: center;
 }
.box {
    
    background-color: red;
}

5. Table 但是父级别有固定宽高

.container {
    display: table-cell;
    vertical-align: middle;
    text-align: center;
    width: 300px;
    height: 300px;
    background-color: royalblue;
 }
.box {
    background-color: red;
    display: inline-block;
    
}