James P.
James P.

Reputation: 19607

Vertically centering an image with max-height and max-width

I have the following html code:

<div style="border: 3px coral solid;width:400px;height:400px;background:#D4D0C8;">
    <img style="max-width:400px;max-height:400px;" src="myImage.jpg">
</div>

Using these styles images with a width > 400 pixels are resized but remain at the top of the div. Is there some way to vertically center them?

Upvotes: 10

Views: 18553

Answers (2)

James P.
James P.

Reputation: 19607

Ok, I seem to have found where the problem lies. The image does center properly on the link provided because it is inside an iframe. Inside a normal page flow the image will display at the top of it's enclosing container.

As table et display: table-cell are broken in IE the fix requires a minimal enclosing table:

<html>
<head>
<style type="text/css">
#content { border:solid 1px;}   
img{ max-width:400px;max-height:400px;margin:auto;}
#page-table {
    height: 400px;
    width: 400px;
    border-collapse: collapse;
    text-align: center;
    border:solid 1px;
}
#page-td {
    height: 100%;
    padding: 0;
    vertical-align: middle;
}

div#content2{
    border:solid 1px;
    width: 400px;
    height: 400px;
    /*line-height: 400px;*/
    text-align: center;
    display: table-cell;
    vertical-align: middle;
}
img#image2 {
    max-width:400px;
    max-height:400px;
    vertical-align: middle;
}
div#enclosingdiv2 {
    border:solid 1px;
}

</style>
</head>
<body>

With table:
<table id="page-table"><tr><td id="page-td">
<div id="content">
<img src="http://lorempixum.com/250/250/abstract">
</div>
</td></tr></table>

Without:
<div id="content2">
<div id="enclosingdiv2">
<img id="image2" src="http://lorempixum.com/250/250/abstract">
<div>
</div>

</body>
</html>

Upvotes: 0

NGLN
NGLN

Reputation: 43649

CSS:

div {
    border: 3px solid coral;
    width: 400px;
    height: 400px;
    background: #d4d0c8;
    line-height: 400px;
    text-align: center;
}
img {
    max-width:400px;
    max-height:400px;
    vertical-align: middle;
}

See demo fiddle.

Upvotes: 12

Related Questions