Question
How can you align an image inside of a containing div
?
Example
In my example, I need to vertically center the <img>
in the <div>
with class ="frame
" :
<div class="frame" style="height: 25px;">
<img src="http://jsfiddle.net/img/logo.png" />
</div>
.frame
's height is fixed and image's height is unknown. I can add new elements in .frame
if that's the only solution. I'm trying to do this on IE≥7, Webkit, Gecko.
See the jsfiddle here
.frame {
height: 25px; /* equals max image height */
line-height: 25px;
width: 160px;
border: 1px solid red;
text-align: center; margin: 1em 0;
}
img {
background: #3A6F9A;
vertical-align: middle;
max-height: 25px;
max-width: 160px;
}
<div class=frame>
<img src="http://jsfiddle.net/img/logo.png" height=250 />
</div>
<div class=frame>
<img src="http://jsfiddle.net/img/logo.png" height=25 />
</div>
<div class=frame>
<img src="http://jsfiddle.net/img/logo.png" height=23 />
</div>
<div class=frame>
<img src="http://jsfiddle.net/img/logo.png" height=21 />
</div>
<div class=frame>
<img src="http://jsfiddle.net/img/logo.png" height=19 />
</div>
<div class=frame>
<img src="http://jsfiddle.net/img/logo.png" height=17 />
</div>
<div class=frame>
<img src="http://jsfiddle.net/img/logo.png" height=15 />
</div>
<div class=frame>
<img src="http://jsfiddle.net/img/logo.png" height=13 />
</div>
<div class=frame>
<img src="http://jsfiddle.net/img/logo.png" height=11 />
</div>
<div class=frame>
<img src="http://jsfiddle.net/img/logo.png" height=9 />
</div>
<div class=frame>
<img src="http://jsfiddle.net/img/logo.png" height=7 />
</div>
<div class=frame>
<img src="http://jsfiddle.net/img/logo.png" height=5 />
</div>
<div class=frame>
<img src="http://jsfiddle.net/img/logo.png" height=3 />
</div>
The old JSFiddle link I posted here didnt work anymore, thats probably the reason for the downvote. Just for the sake of this being a valid answer i still want to post the jQuery solution again. This works for every element that has the
v_align
class applied to it. It will be vertical centered in the parent and on resizing of the window it will be recalculated.Link to the JSFiddle
3 line solution:
This applies to anything.
From here.
A PURE CSS Solution:
http://jsfiddle.net/3MVPM/
The CSS:
Key stuff
matejkramny's solution is a good start, but oversized images have a wrong ratio.
Here's my fork:
demo: https://jsbin.com/lidebapomi/edit?html,css,output
HTML:
CSS:
This way you can center an image vertically (demo):
There is a super easy solution with flexbox!