css3

水平垂直居中

<div class="wp">
  <div class="box size">123123</div>
</div>
  1. 定位+负 margin
.wp {
  position: relative;
}
.box {
  position: absolute;
  top: 50%;
  left: 50%;
  margin-left: -50px;
  margin-top: -50px;
}
  1. absolute + margin auto
.wp {
  position: relative;
}
.box {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  margin: auto;
}
  1. absolute + calc
.wp {
  position: relative;
}
.box {
  position: absolute;
  top: calc(50% - 50px);
  left: calc(50% - 50px);
}
  1. 定位+ transform
.wp {
  position: relative;
}
.box {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
  1. lineheight
.wp {
  line-height: 300px;
  text-align: center;
  font-size: 0px;
}
.box {
  font-size: 16px;
  display: inline-block;
  vertical-align: middle;
  line-height: initial;
  text-align: left; /* 修正文字 */
}
  1. writing-mode (通过 writing-mode 让文字的显示变为垂直方向)
<div class="wp">
  <div class="wp-inner">
    <div class="box">123123</div>
  </div>
</div>
.wp {
  writing-mode: vertical-lr;
  text-align: center;
}
.wp-inner {
  writing-mode: horizontal-tb;
  display: inline-block;
  text-align: center;
  width: 100%;
}
.box {
  display: inline-block;
  margin: auto;
  text-align: left;
}
  1. css-table
.wp {
  display: table-cell;
  text-align: center;
  vertical-align: middle;
}
.box {
  display: inline-block;
}
  1. flex
  2. grid(和 flex 同理)
.wp {
  display: grid;
}
.box {
  align-self: center;
  justify-content: center;
}
上次更新: