Why `position:absolute;` destroy ` vertical-align:middle`?



文本center位于div的中心,如下面的代码所示。

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

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

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

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

position: absolute赋给diplay:table-cell将强制其为display: block,并且vertical-align: middle;不能用于块元素

更多信息

你可以把Absolute-Center

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

position: absolute中断了display: table / table-cell,所以你需要使用padding/50%的element's高度的centered

应该像下面这样正确使用flexbox

Use This:

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

你可以使用CSS Flexbox

请看下面的代码:

.Absolute-Center { 
  position: absolute;
  display: flex; /* Flexbox Property */
  justify-content: center; /* Horizontal Centering */
  align-items: center; /* Vertical Centering */
  width: 100px;  
  height: 100px; 
  border:1px solid red;
}
<div class="Absolute-Center">
    <p>center</p>
</div>

希望这对你有帮助!

最新更新