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>
SOLUTION USING TABLE & TABLE CELL
Sometimes it should be solved by displaying as table/table-cell. For example a fast title screen. It is a recommended way by W3 also. I recommend you check this link called Centering things from W3C.org
The tips used here are:
Personally I actually disagree about use helpers for this purpose
The best solution is that
Not sure about IE, but under Firefox and Chrome, if you have a
img
in adiv
container, the following css should work. At least for me works well:If you can live with pixel-sized margins, just add
font-size: 1px;
to the.frame
. But remember, that now on the.frame
1em = 1px, which means, you need to set the margin in pixels too.http://jsfiddle.net/feeela/4RPFa/96/
EDIT: now its not centered anymore in Opera…
For centering an image inside a container (it could be a logo) besides some text like this:
Basically you wrap the image
For those that landed on this post and are interested in a more modern solution, and that have no need to support legacy browsers, you can do this:
Here's a Pen: http://codepen.io/ricardozea/pen/aa0ee8e6021087b6e2460664a0fa3f3e