4

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>
        &nbsp;
        <span class="small inline">A Very Small Text</span>
        &nbsp;
        <span class="medium inline">Medium String</span>
    </span>
</div>

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.

Community
  • 1
  • 1
marcoseu
  • 3,892
  • 2
  • 16
  • 35
  • Answers from @lazyprogrammer and @j08691 are perfectly fine and have the least needed instructions but if you also want to align text (not by their respective baseline) then check my answer, that needs to use `inline-block` – FelipeAls May 10 '13 at 16:55

2 Answers2

6

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/

HTML:

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

CSS:

.vam {
    vertical-align: middle;
}
span.vam {
    display: inline-block;
}
.vam img {
    vertical-align: top; /* removes a white gap below image */
}
FelipeAls
  • 21,711
  • 8
  • 54
  • 74
1

Your problem can be solved by adding the following code

.inline img{
   vertical-align:middle;
 }

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

.yourDiv{
    height:50px;
    line-height:50px;
 } 

jsfiddle

lazyprogrammer
  • 633
  • 9
  • 26