超大图像居中,最大宽度和最大高度

时间:2014-11-09 21:45:20

标签: css image

我有一个包含图片的img标签,需要缩小到最大宽度:200px或最大高度:200px,这取决于图像是高还是宽。我目前的代码:

CSS:

div#music_artwork {
    position: relative;
    width: 200px;
    height:200px;
    background:#eee;
}
.img-container {
    position: relative;
    overflow: hidden;
    width:200px;
    height:200px;
}

img {
    position: absolute;
    top: -9999px;
    bottom: -9999px;
    left: -9999px;
    right: -9999px;
    margin: auto;   
}

HTML:

<div id="music_artwork">
    <div class="img-container">
        <img class="first" src="http://entertainmentmv.nl/wp-content/uploads/2014/06/breaking-1.png">
    </div>
</div>

您将看到两个包含图像的容器。其中一个很高,其中一个很宽。我正在寻找一种在没有JavaScript的情况下组合这些代码的方法。

JSFiddle中的代码(http://jsfiddle.net/L9BnL/298/

1 个答案:

答案 0 :(得分:1)

CSS目前无法检测图像的方向并根据该信息应用不同的规则。但是,如果您能够更改HTML并使用背景图片而不是img标记,则可以使用background-size: cover;轻松解决此问题。此外,所需的总CSS更清晰。

请注意:目前仅适用于Chrome和Opera,部分支持Safari。 Firefox和IE不支持该功能。有关详细信息,请参阅http://caniuse.com/#search=cover

.img-container {
    width: 200px;
    height: 200px;
    margin: 20px;
    background-size: cover;
}
<div class="music_artwork">
    <div class="img-container" style="background-image: url('http://entertainmentmv.nl/wp-content/uploads/2014/06/breaking-1.png');">
    </div>
</div>

<div class="music_artwork" style="margin-top:20px;">
    <div class="img-container" style="background-image: url('http://cdn1.sciencefiction.com/wp-content/uploads/2013/08/Bryan-Cranston.jpg');">
    </div>
</div>