CSS 拷问:水平垂直居中方法你会几种?

  1. <div class="outer">
  2. <div class="inner">hello world</div>
  3. </div>
  4. .outer {
  5. width: 300px;
  6. height: 300px;
  7. border: 1px solid #999;
  8. }
  9. .inner {
  10. width: 100px;
  11. height: 100px;
  12. border: 1px solid #999;
  13. }

水平垂直居中

  1. Flex 方案
  2. Grid 方案
  3. absolute + transform
  4. absolute + calc
  5. absolute + 负 margin
  6. absolute + margin: auto
  7. writing-mode

    Flex方案

    ``` / 这里引用复用代码 /

.outer { display: flex; justify-content: center; / 水平居中 / align-items: center; / 垂直居中 / } / 另一种用法/ .outer { display: flex; }

.inner { margin: auto; }

<a name="k2Z6J"></a>
#### Grid 方案

/ 这里引用复用代码 /

.outer { display: grid; }

.inner { justify-self: center; / 水平居中 / align-self: center; / 垂直居中 / } /另一种用法/ .outer { display: grid; }

.inner { margin: auto; }

<a name="Ji3FQ"></a>
#### absolute + transform

.outer { position: relative; }

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

<a name="CIqws"></a>
#### absolute + calc

.outer { position: relative; }

.inner { position: absolute; left: calc(50% - 50px); top: calc(50% - 50px); }

<a name="Rwllm"></a>
#### absolute + 负 margin

.outer { position: relative; }

.inner { position: absolute; left: 50%; top: 50%; margin-left: -50px; margin-top: -50px; }

<a name="ASGNV"></a>
#### absolute + margin:auto

.outer { position: relative; }

.inner { position: absolute; left: 0; right: 0; top: 0; bottom: 0; margin: auto; } ```

writing-mode

writing-mode 可以改变文字显示方向。例如,将文字显示为垂直方向: