James Hay
James Hay

Reputation: 7325

Vertical center an image

I'm trying to use the line-height, vertical-align method to center an image inside a div. Looking at examples, questions on here, and other fixes they all suggest and even show that this works. Yet it's not working for me.

Basic structure

<div class="photo_container">
    <img alt="" src="photos/1.jpg" class="thumbnail" />
</div>

CSS

div.photo_container
{
    width: 160px;
    height: 160px;
    padding: 10px;
    float: left;
    margin-right: 10px;
    margin-bottom: 10px;
    background-color: White;
    box-shadow: 0px 0px 5px #AAA;
    text-align: center;
    line-height: 160px;
}
img.thumbnail
{
    vertical-align: middle;   
}

Basically, the container is always 160px high as you can see, but the image inside could be something like 100px high. In this case I want there to be 30px spacing at the top and the bottom of the container and for my image to be vertically aligned in the middle.

What am I missing?

ANSWERED

Turns out it was a DOCTYPE problem, I was using the

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

when I should have been using the HTML 5 doctype

<!DOCTYPE html>

Upvotes: 1

Views: 323

Answers (4)

Eran Medan
Eran Medan

Reputation: 45735

This seems to work for me more or less

See in JSFiddle

CSS

div.photo_container
{
    width: 160px;
    height: 160px;
    padding: 10px;
    float: left;
    margin-right: 10px;
    margin-bottom: 10px;
    background-color: White;
    box-shadow: 0px 0px 5px #AAA;
    text-align: center;
    line-height: 160px;
    border: 1px solid red;
}
img.thumbnail
{
    vertical-align: middle;   
}​

HTML

<div class="photo_container">
    <img alt="" src="http://www.totalesl.com/images/icon/funny-icon.jpg" class="thumbnail" />
</div>​

Upvotes: 0

reisio
reisio

Reputation: 3242

A doctype declaration: <!doctype html>

(Or, alternatively: valid code)

Upvotes: 1

Jim Thomas
Jim Thomas

Reputation: 1658

Your code seems to work for me in chrome.. fiddle below. Is there something I'm missing?

Edit: I did add a width/height to the non-existant image.

JS Fiddle

Upvotes: 1

Dennis
Dennis

Reputation: 338

http://css-tricks.com/snippets/css/absolute-center-vertical-horizontal-an-image/

This should explain how to do it.

Upvotes: 0

Related Questions