How to middle-align text and image in an html page
Monday, 9. April 2007, 23:08:18
So today I put some time aside to solve this problem once and for all the time and publish the results on my weblog.
So, lets go. Suppose that you have an image with a height of 32 pixels and you want to middle-align it next to some 12px text. Here is one possible solution:
<div style="font-size: 12px;"> <img src="32.png" style="padding-bottom: 4px; vertical-align: middle;"/> Some 12px Text </div>
The trick is the 4px bottom padding for the image. I came up with 4px with trial and error. Lets look at another example: aligning a 12px-height image with 12px text:
<div style="font-size: 12px;"> <img src="12.png" style="padding-bottom: 4px; vertical-align: middle;"/> Some 12px Text </div>
As a last example, lets middle align a 32px height image with a 64px sized text:
<div style="font-size: 64px;"> <img src="32.png" style="padding-bottom: 12px; vertical-align: middle;"/> Some 12px Text </div>

Note that the above examples ware tested only in an xhtml transitional page, and on IE 6, Opera, and Firefox.
Conclusion:
Styling the image vertical-align: middle is not enough. Sometimes you need to fix the padding-bottom style of the image in order to middle-align text and image pixel perfect.









Anonymous # 17. June 2007, 10:06
Note: This entry and its follow ups looked like to be spam, so I have deleted them.
Anonymous # 19. June 2008, 22:21
good tip, thanks. was struggling with this too.
Anonymous # 8. November 2008, 19:38
Finally can align an image correctly! Thanks for your support!
Anonymous # 12. November 2008, 04:23
thank you!
Hannah Fisher # 31. December 2008, 03:43
Pig Milk
Anonymous # 3. February 2009, 16:03
Great thanks for this. So how could you align another picture on the right, and keep the text in absolute middle? so picture - text - picture.
Behrang Saeedzadeh # 4. February 2009, 01:36
Anonymous # 18. February 2009, 19:52
Thanks so much for this one, what a pain this can be!
Anonymous # 4. March 2009, 15:51
Thank you so much this has saved me!!!
Anonymous # 13. April 2009, 18:22
Simple yet an excellent fix. Thanks man!
Anonymous # 17. April 2009, 08:05
Yeah baby,
you made my day :)
Finally - I have been struggeling around with that sh&%$ for so long.
Cheers from Germany!
Behrang Saeedzadeh # 17. April 2009, 09:46
LOL. You're welcome man :-)
Anonymous # 28. April 2009, 11:38
Fantastic just what i needed :D
Anonymous # 5. June 2009, 18:17
Thank you very much.
Anonymous # 24. June 2009, 10:08
nice
Anonymous # 12. October 2009, 18:14
Thanks mate! Works fine...
Anonymous # 30. October 2009, 09:25
Thanks!
:D
Anonymous # 20. November 2009, 10:32
Thanks for the code snippet helped a lot.
Anonymous # 2. December 2009, 11:05
Teşekkürler from TURKEY, (Thank You)
Anonymous # 17. December 2009, 14:43
Thanks man, There is a lot less headbanging going on in the world thanks to your patient examples!