我不相信你可以用 CSS 做到这一点。我尝试用一些简单的 JS 来做,效果很好:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style media="all">
div {width: 700px; background: #e7e7e7;}
img {width: 100%;}
</style>
</head>
<body>
<div>
<img src="600x400.jpg" >
<br>
<br>
<img src="400x600.jpg">
</div>
<script>
window.onload = imgSizer;
function imgSizer()
{
"use strict";
var d = document, imgs, i, ii;
imgs = d.getElementsByTagName("img");
for (i=0, ii=imgs.length; i<ii; i+=1)
{
if (imgs[i].height > "800")
{
imgs[i].setAttribute("style", "height:800px; width: auto;");
} else {
imgs[i].style.maxWidth = "100%";
}
}
}
</script>
</body>
</html>
不过,我对 JS 完全陌生,所以可能有更好的方法来做到这一点。您还可以在此处查看示例:http: //codepen.io/anon/pen/EsIBi
如果你愿意,你可以使用一些 jQuery 来解决这个问题:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style media="all">
#content {width: 700px; background: #e7e7e7;}
img {width: 100%;}
</style>
</head>
<body>
<div id="content">
<img src="http://pageaffairs.com/sp/so-16368859/600x400.jpg" >
<br>
<br>
<img src="http://pageaffairs.com/sp/so-16368859/400x600.jpg">
</div>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
<script>
$(document).ready(function() {
var imgs = $("#content").children('img');
for (var i=0, ii=imgs.length; i<ii; i+=1)
{
if (imgs[i].height > "800")
{
imgs[i].setAttribute("style", "height:800px; width: auto;");
} else {
imgs[i].style.maxWidth = "100%";
}
}
});
</script>
</body>
</html>