Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to vertical align elements inside a div

Tags:

html

css

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.

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

marcoseu


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/

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 */
}
like image 171
FelipeAls Avatar answered Mar 28 '23 03:03

FelipeAls


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

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

lazyprogrammer