it_is_a_literature it_is_a_literature - 24 days ago 15
CSS Question

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

The text

center
is located at the center of div such as below code show.



.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>





Now to add a line
position:absolute;
in the css of
.Absolute-Center
.



.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>





The text
center
was not at the center of div now ,why
position:absolute;
can result in this?

Answer

position: absolute interrupts on display: table / table-cell, so you need to centered using padding / 50% line-height of that element's height.

Instead use the flexbox properly like below.

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>

Comments