相同宽高比的图像占位符,最大宽度和宽度高度

时间:2016-04-16 09:45:31

标签: html css image

此HTML在等待加载图片时创建图像占位符:<img src="http://placehold.it/1366x667" width="1366" height="667"> [1]

此CSS设置图像大小的限制而不会偏移宽高比[2]:

img { max-width: 50%; max-height: 50vh; }

但是当我同时使用它们时,它不会保持纵横比。[3]

在获取图像之前,我该怎么做才能使图像尺寸正确,保持纵横比?我宁愿在纯CSS中这样做,但这不是必需的。我已经尝试将CS​​S widthheight设置为auto,但在获取图片之前,图片大小似乎未知。

[1] http://jsbin.com/poluyociya/1/edit?html,css,output

[2] http://jsbin.com/yejezafiqi/1/edit?html,css,output

[3] http://jsbin.com/diruromela/3/edit?html,css,output

1 个答案:

答案 0 :(得分:0)

如果我理解你的问题,你需要这样的事情:

&#13;
&#13;
img {
  max-width: 50%;
  height:auto;
  /*To check if aspect-ratio is preserved*/
  background-color: red;
}
&#13;
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
<img src="http://placehold.it/1366x667" width="1366" height="667">
</body>
</html>
&#13;
&#13;
&#13;

相关问题