Search code examples
cssvertical-alignment

Vertically align text within a div


The code below (also available as a demo on JS Fiddle) does not position the text in the middle, as I ideally would like it to. I cannot find any way to vertically centre text in a div, even using the margin-top attribute. How can I do this?

<div id="column-content">
    <img src="https://i.sstatic.net/12qzO.png">
    <strong>1234</strong>
    yet another text content that should be centered vertically
</div>
#column-content {
    display: inline-block;
    border: 1px solid red;
    position:relative;
}
    
#column-content strong {
    color: #592102;
    font-size: 18px;
}

img {
    margin-top:-7px;
    vertical-align: middle;        
}

Solution

  • Andres Ilich has it right. Just in case someone misses his comment...

    A.) If you only have one line of text:

    div
    {
      height: 200px;
      line-height: 200px; /* <-- this is what you must define */
    }
    <div>vertically centered text</div>

    B.) If you have multiple lines of text:

    div
    {
      height: 200px;
      line-height: 200px;
    }
    
    span
    {
      display: inline-block;
      vertical-align: middle;
      line-height: 18px; /* <-- adjust this */
    }
    <div><span>vertically centered text vertically centered text vertically centered text vertically centered text vertically centered text vertically centered text vertically centered text vertically centered text vertically centered text vertically centered text</span></div>