以max-height和max-width对图像垂直居中



我有以下html代码:

<div style="border: 3px coral solid;width:400px;height:400px;background:#D4D0C8;">
    <img style="max-width:400px;max-height:400px;" src="myImage.jpg">
</div>
使用这些样式,宽度> 400像素的图像被调整大小,但仍然在div的顶部。是否有一些方法可以垂直居中?

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;
}

好了,我好像找到问题所在了。由于图像位于iframe内,因此它不会正确地位于所提供的链接的中心。在一个正常的页面流中,图像将显示在它的封闭容器的顶部。

由于table et display: table-cell在IE中被破坏,修复需要一个最小的封闭表:

<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>

最新更新