css垂直水平居中方法

96 阅读1分钟

1.弹性盒display:flex

.box {
    width: 500px;
    height: 500px;
    background-color: aliceblue;
    border: 1px solid #000;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  .main {
    width: 100px;
    height: 100px;
    background: red;
  }

2.display: grid;

.box {
    width: 500px;
    height: 500px;
    background-color: aliceblue;
    border: 1px solid #000;
    display: grid;
    place-items: center;
  }
  .main {
    width: 100px;
    height: 100px;
    background: red;
  }

3.父容器相对定位,子容器绝对定位,transform:translate(-50%, -50%);

.box {
    width: 500px;
    height: 500px;
    background-color: aliceblue;
    border: 1px solid #000;
    position: relative;
  }
  .main {
    width: 100px;
    height: 100px;
    background: red;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
  }

4.父容器相对定位,子容器绝对定位,margin: 负值

.box {
    width: 500px;
    height: 500px;
    background-color: aliceblue;
    border: 1px solid #000;
    position: relative;
  }
  .main {
    width: 100px;
    height: 100px;
    background: red;
    position: absolute;
    top: 50%;
    left: 50%;
    margin-top: -50px;
    margin-left: -50px;
  }

5.父容器相对定位,子容器绝对定位,margin: auto;

.box {
    width: 500px;
    height: 500px;
    background-color: aliceblue;
    border: 1px solid #000;
    position: relative;
  }
  .main {
    width: 100px;
    height: 100px;
    background: red;
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    margin: auto;
  }