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>
</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.
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>
<span class="small vam">A Very Small Text</span>
<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 */
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With