<div class="level">
  <h1>水平居中</h1>

  <div class="wrapper wrapper1">
    <span>行内,text-align: center;</span>
  </div>

  <div class="wrapper wrapper2">
    <div>
      块元素
      <p>(定宽度)</p>
      <p>margin: 0 auto</p>
    </div>
  </div>

  <div class="wrapper wrapper3">
    <div>块元素(不定宽度)</div>
  </div>

  <div class="wrapper wrapper4">
    <div>
      块元素
      <p>flex实现</p>
      <p>(定不定宽度可以)</p>
    </div>
  </div>
</div>

<div class="vertical">
  <h1>垂直居中</h1>

  <div class="wrapper wrapper5">
    <span>单行的行内元素,设置行高</span>
  </div>

  <div class="wrapper wrapper6">
    <span>多行的行内元素,多行的行内元素,多行的行内元素,多行的行内元素,多行的行内元素,多行的行内元素</span>
  </div>
  <br />

  <div class="wrapper wrapper7">
    <div>块级元素(定高度)</div>
  </div>

  <div class="wrapper wrapper8">
    <div>
      块级元素
      <p>flex实现</p>
      <p>(定不定高度可以)</p>
    </div>
  </div>
</div>

<div class="levelVertical">
  <h1>水平垂直居中</h1>

  <div class="wrapper wrapper9">
    <div>
      块级元素
      <p>已知宽高</p>
    </div>
  </div>

  <div class="wrapper wrapper10">
    <div>
      块级元素
      <p>已知宽高</p>
    </div>
  </div>

  <div class="wrapper wrapper11">
    <div>
      块级元素
      <p>未知宽高</p>
    </div>
  </div>

  <div class="wrapper wrapper12">
    <div>
      块级元素
      <p>flex实现</p>
      <p>未知宽高</p>
    </div>
  </div>
</div>
.level,
.vertical,
.levelVertical {
  float: left;
  margin: 10px;
  font-size: 15px;
}
h1 {
  text-align: center;
}
.wrapper {
  width: 240px;
  height: 150px;
  background: #eee;
  margin-bottom: 20px;
}
.wrapper > div {
  background: coral;
}

.wrapper1 {
  text-align: center;
}

.wrapper2 div {
  width: 100px;
  margin: 0 auto;
}

.wrapper3 {
  text-align: center;
}
.wrapper3 div {
  display: inline;
}

.wrapper4 {
  display: flex;
  justify-content: center;
}

.wrapper5 {
  line-height: 150px;
}

.wrapper6 {
  display: table-cell;
  vertical-align: middle;
}

.wrapper7 {
  position: relative;
}
.wrapper7 div {
  height: 100px;
  position: absolute;
  top: 50%;
  margin-top: -50px;
}

.wrapper8 {
  display: flex;
  align-items: center;
}

.wrapper9 {
  position: relative;
}
.wrapper9 div {
  width: 100px;
  height: 100px;
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  margin: auto;
}

.wrapper10 {
  position: relative;
}
.wrapper10 div {
  width: 100px;
  height: 100px;
  position: absolute;
  left: 50%;
  top: 50%;
  margin-left: -50px;
  margin-top: -50px;
}

.wrapper11 {
  position: relative;
}
.wrapper11 div {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translateX(-50%) translateY(-50%);
}

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

External CSS

This Pen doesn't use any external CSS resources.

External JavaScript

This Pen doesn't use any external JavaScript resources.