为什么`position:absolute;`destroy`vertical-align:middle`?

it_*_*ure 5 html css

文本center位于div的中心,如代码show下方.

.Absolute-Center { 
  display: table-cell;
  width: 100px;  
  height: 100px; 
  border:1px solid red; 
  text-align:center;
  vertical-align:middle;
  } 
Run Code Online (Sandbox Code Playgroud)
<div class="Absolute-Center">
    <p>center</p>
</div>
Run Code Online (Sandbox Code Playgroud)

现在position:absolute;在css中添加一行.Absolute-Center.

.Absolute-Center { 
  position:absolute;
  display: table-cell;
  width: 100px;  
  height: 100px; 
  border:1px solid red; 
  text-align:center;
  vertical-align:middle;
  } 
Run Code Online (Sandbox Code Playgroud)
<div class="Absolute-Center">
    <p>center</p>
</div>
Run Code Online (Sandbox Code Playgroud)

文本center现在不在div的中心,为什么position:absolute;会导致这个?

Jim*_*had 2

position: absolute中断display: table / table-cell,因此您需要centered使用padding/ 该高度的 50% 行高element's

相反,请flexbox正确使用如下所示。

用这个:

.Absolute-Center {
  border: 1px solid red;
  display: flex;
  flex-flow: column nowrap;
  height: 100px;
  justify-content: center;
  position: absolute;
  text-align: center;
  width: 100px;
}
Run Code Online (Sandbox Code Playgroud)
<div class="Absolute-Center">
    <p>center</p>
</div>
Run Code Online (Sandbox Code Playgroud)