1

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>
Shafizadeh
  • 9,086
  • 10
  • 43
  • 80
  • 1
    Possible duplicate of [How to align text vertically center in div with CSS?](http://stackoverflow.com/questions/8865458/how-to-align-text-vertically-center-in-div-with-css) and a host of other answers to this question which seems to get asked every day. – Rob Nov 15 '15 at 14:47

3 Answers3

4

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>
Robin Carlo Catacutan
  • 11,461
  • 9
  • 48
  • 79
2

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.

bowheart
  • 4,340
  • 1
  • 21
  • 23
  • What happens if I use `::before` instead of `::after`? I tested it, I did not get any difference .. – Shafizadeh Nov 15 '15 at 06:40
  • 1
    Nope, there should be no difference in this context since the `::after` is supposed to be hidden anyway. The only difference between `::before` and `::after` is DOM order (which affects natural stacking, etc...). But in this case, since the pseudo-element will be invisible, we don't care about that. Either one will work. – bowheart Nov 15 '15 at 06:46
1

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>
Jinu Kurian
  • 7,776
  • 2
  • 21
  • 33