10种水平垂直居中,你更中意哪一个

大概布局:

1.flex布局直接父级来

.father {
  display: flex;
  justify-content: center;
  align-items: center;
}

2.子级自己解决

.father {
  display: flex;
  .son{
    align-self: center;
    margin: auto;
  }
}

3.grid

.father {
  display: grid;
  .son{
    margin: auto;
  }
}

4.grid

.father {
  display: grid;
  .son{
    justify-self: center;
    align-self: center;
  }
}

5.calc() 函数

.father {
  .son{
    margin: calc(50% - 50px) auto 0 auto;
  }
}

6.

.father {
  position: relative;
  .son{
    position: absolute;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    margin: auto;
  }
}

7.

.father {
  display: flex;
  .son{
    margin: auto;
  }
}

8.

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

9.table-cell

.father {
  display: table-cell;
  vertical-align: middle;
  text-align: center;
  .son{
    display: inline-block;
  }
}

10.最后一种是相对文本来说,

text-align:center;
line-height: **px;

猜你喜欢

转载自blog.csdn.net/ChasenZh/article/details/110210618