Shafizadeh
Shafizadeh

Reputation: 10340

Vertical Centering - How to keep an inline element in the middle of a block-level element vertically

I have a <div> that is containing a sentence. The height of <div> is based of % (its height is changeable - depends on size of screen). Now I want to keep that sentence in the center (vertically) of <div>, How can I do that?

Here is a sample of what I said:

div{
  position:absolute;
  border: 1px solid;
  width: 250px;
  height: 60%;
  text-align: center;
}
<div>This should be center vertically</div>

Upvotes: 1

Views: 117

Answers (3)

Jinu Kurian
Jinu Kurian

Reputation: 9406

Seen two methods already. Here is another method using table and table-cell. give display: tableto parent and table-cell and vertical-align: middle to the child and see the magic.

div{
  position:absolute;
  border: 1px solid;
  width: 250px;
  display: table;
  height: 60%;
  text-align: center;
}
div span {
  display: table-cell;
  vertical-align: middle;
}
<div><span>This should be centered vertically</span></div>

Upvotes: 1

bowheart
bowheart

Reputation: 4676

My favorite technique is to add an ::after pseudo-element to the parent element, wrap all the element's children in a single element, and let that element and the ::after pseudo-element play the inline-block, vertical-alignment game:

div{
  position:absolute;
  border: 1px solid;
  width: 250px;
  height: 60%;
  text-align: center;
}
div span {
  display: inline-block;
  vertical-align: middle;
}
div::after {
  content: '';
  display: inline-block;
  height: 100%;
  vertical-align: middle;
}
<div><span>This should be centered vertically, and now it is!</span></div>

The ::after pseudo-element having height: 100% will expand dynamically with the height of the parent, thus the inner element will always be centered vertically.

Upvotes: 2

Robin Carlo Catacutan
Robin Carlo Catacutan

Reputation: 13679

Use flexbox

div{
  position:absolute;
  border: 1px solid;
  width: 250px;
  height: 60%;
  text-align: center;
  display: flex;
  align-items: center;
  justify-content: center;
}
<div>This should be center vertically</div>

Upvotes: 4

Related Questions