我會做這樣的事情。我希望這個解決方案有幫助
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
.img-cont {
border: solid 1px red;
width: 300px; /* reference border */
height: 300px;
}
</style>
</head>
<body>
<!-- images with different dimensions -->
<div class="img-cont"><img src="https://dummyimage.com/800x400/000/fff" alt=""/></div>
<div class="img-cont"><img src="https://dummyimage.com/400x800/000/fff" alt=""/></div>
<div class="img-cont"><img src="https://dummyimage.com/100x200/000/fff" alt=""/></div>
<div class="img-cont"><img src="https://dummyimage.com/200x100/000/fff" alt=""/></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
(function($) {
// max image width/height that we want
var maxWidthAllowed = 300,
maxHeightAllowed = 300;
function loadImg(imgObj) {
$('.img-cont img').one("load", function() {
var imgWidth = $(this).get(0).naturalWidth,
imgHeight = $(this).get(0).naturalHeight,
coeff = imgWidth/imgHeight; // get image proportion
if(parseFloat(coeff) > 1) {
// wide image
// resize proportionately
$(this).css({
'max-width': maxWidthAllowed,
'width': '100%',
'height' : 'auto'
});
} else {
// thin image
// resize proportionately
$(this).css({
'max-height': maxHeightAllowed,
'height': '100%',
'width' : 'auto'
});
}
}).each(function() {
if(this.complete) $(this).load();
});
}
loadImg();
})(jQuery);
</script>
</body>
</html>
所以你需要一個純粹的CSS解決方案或JavaScript也可以接受? –
爲什麼不只設置高度或寬度?而不是設置高度和寬度。 –
而不是圖片,將它設置爲div的背景,background-size:cover; background-position:center;應該適合放在背景中的圖像放在中心 – santosh