Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

html

css

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?

like image 910
showkey Avatar asked Nov 09 '16 07:11

showkey


2 Answers

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>
like image 30
Jim Fahad Avatar answered Nov 15 '22 08:11

Jim Fahad


Giving position: absolute to diplay:table-cell will force it to be display: block, and vertical-align: middle; does not work with block elemets

More Info

you can wrap 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>
like image 117
Abhishek Pandey Avatar answered Nov 15 '22 07:11

Abhishek Pandey