[html] How do I vertical center text next to an image in html/css?

What is the best and easiest way to vertically center text that's next to an image in html? Needs to be browser version/type agnostic. A pure html/CSS solution.

This question is related to html css

The answer is


There are a couple of options:

  • You can use line-height and make sure it is tall as the containing element
  • Use display: table-cell and vertical align: middle

My preferred option would be the first one, if it's a short space, or the latter otherwise.


Since most of the answers to this question are between 2009 and 2014 (except for a comment in 2018), there should be an update to this.

I found a solution to the wrap-text problem brought up by Spongman on Jun 11 '14 at 23:20. He has an example here: jsfiddle.net/vPpD4

If you add the following in the CSS under the div tag in the jsfiddle.net/vPpD4 example, you get the desired wrap-text effect that I think Spongman was asking about. I don't know how far back this is applicable, but this works in all of the current (as of Dec 2020/Jan 2021) browsers available for Windows computers. Note: I have not tested this on the Apple Safari browser. I have also not tested this on any mobile devices.

    div img { 
        float: left;
    }
    .clearfix::after {
        content: ""; 
        clear: both;
        display: table;
    }

I also added a border around the image, just so that the reader will understand where the edge of the image is and why the text wraps as it does. The resulting example looks is here: http://jsfiddle.net/tqg7hLzk/


There are to ways: Use the attribute of the image tag align="absmiddle" or locate the image and the text in a container DIV or TD in a table and use

style="vertical-align:middle"

One basic way that comes to mind would be to put the item into a table and have two cells, one with the text, the other with the image, and use style="valign:center" with the tags.


That's a fun one. If you know ahead of time the height of the container of the text, you can use line-height equal to that height, and it should center the text vertically.


Does "pure HTML/CSS" exclude the use of tables? Because they will easily do what you want:

<table>
    <tr>
        <td valign="top"><img src="myImage.jpg" alt="" /></td>
        <td valign="middle">This is my text!</td>
    </tr>
</table>

Flame me all you like, but that works (and works in old, janky browsers).


I recommend using tables with <td valign="middle"> (as inkedmn mentioned, it works in all browsers), but if you're wrapping with a link, here's how to do it (works in ugly old browsers too, like Opera 9):

<a href="/" style="display: block; vertical-align: middle;">
    <img src="/logo.png" style="vertical-align: middle;"/>
    <span style="vertical-align: middle;">Sample text</span>
</a>