Logo Questions Linux Laravel Mysql Ubuntu Git Menu

How to vertical align elements inside a div




I am a HTML/CSS newbie and vertical aligning of elements in side div is driving me crazy. Basically, I have a div that contain a mix of text and images and all I wanted to do is vertically align the elements in the middle of th ediv.

According to this post:

Inline elements (and only inline elements) can be vertically aligned in their context via vertical-align: middle. However, the “context” isn’t the whole parent container height, it’s the height of the text line they’re in.

So, I create a SPAN and event set the diplay: inline but nothing works:

<div id="main_section" class="main_align" >
    <span class="inline">
        <span class="inline"><img src="http://placehold.it/50x50" /></span>
        <span class="small inline">A Very Small Text</span>
        <span class="medium inline">Medium String</span>

Here is the jsfiddle.

Any pointers will be greatly appreciated.

Note: I am happy if this works in Chrome and Firefox. No need to address IE specific issues.

like image 623
marcoseu Avatar asked Mar 25 '23 00:03


2 Answers

EDIT 2018: I tend to use Flexbox a lot nowadays for centering in any direction. inline-block is still fine but Flexbox is so much powerful :)

If you also want to align texts of different sizes vertically (other than by their baseline), than the following fiddle is a possible solution, using inline-block: http://jsfiddle.net/vGKjj/13/


<div id="main_section" class="main_align" >
        <span class="vam"><img src="http://placehold.it/50x50" /></span>
        <span class="small vam">A Very Small Text</span>
        <span class="medium vam">Medium String</span>


.vam {
    vertical-align: middle;
span.vam {
    display: inline-block;
.vam img {
    vertical-align: top; /* removes a white gap below image */
like image 171
FelipeAls Avatar answered Mar 28 '23 03:03


Your problem can be solved by adding the following code

.inline img{

Just another note
Also a trick that works fine, if you have a fixed height, make the line height equal to it.
For example:-



like image 22
lazyprogrammer Avatar answered Mar 28 '23 05:03