Html 如何设置容器高度自动保持比例

Html 如何设置容器高度自动保持比例,html,css,image,layout,Html,Css,Image,Layout,我在div对象中有一个img对象。我想设置img(或div)的宽度,并自动将其高度设置为保留图像原始比率所需的任何值 假设我将宽度设置为200px,它比图像的自然宽度短。当我这样做时: HTML <div id="container"> <img id="foo" src="foo.png"> </div> 或 img将高度设置为保留原始比率所需的任何值,但外部div将高度设置为内部图像的自然高度,并且顶部和底部边距插入内部img和外部div之间 我希望

我在
div
对象中有一个
img
对象。我想设置
img
(或
div
)的宽度,并自动将其高度设置为保留图像原始比率所需的任何值

假设我将宽度设置为
200px
,它比图像的自然宽度短。当我这样做时:

HTML

<div id="container">
  <img id="foo" src="foo.png">
</div>

img
将高度设置为保留原始比率所需的任何值,但外部
div
将高度设置为内部图像的自然高度,并且顶部和底部边距插入内部
img
和外部
div
之间

我希望外部
div
的高度为保留
img
原始比率所需的任何值,以便
div
img
之间的上下边距为零。我该怎么做呢?

试试这段代码

<div class="container">
   <img src="demo.jpg" alt="" />
</div>

body{
    margin: 0;
}
.container{
    width: 200px;
    border: 1px solid red; //tmp added to check the height of container
}

.container img{
    display: block;
    width: 100%;
}

身体{
保证金:0;
}
.集装箱{
宽度:200px;
边框:1px纯红;//添加tmp检查容器高度
}
.集装箱img{
显示:块;
宽度:100%;
}
使用此功能:

 <script type="text/javascript">
 function resizeHeight(){
 var resizedImage = document.getElementById('foo');
 resizedImage.style.height = (resizedImage.style.height * 200)/resizedImage.style.width;
 resizedImage.style.width = '200px';
 }
 </script>

函数resizeHeight(){
var resizedImage=document.getElementById('foo');
resizedImage.style.height=(resizedImage.style.height*200)/resizedImage.style.width;
resizedImage.style.width='200px';
}
并将图像行编辑为:

 <img id="foo" src="foo.png" onload="resizeHeight()">


它应该自动将图片的宽度设置为200,并按比例调整高度。

好问题(+1)。此代码是否适用于具有固定宽度和div的图像,以及具有固定宽度的图像?或者它将应用于具有不同(大小)图像的多个div,并且应该是动态的?@LinkinTED它应该应用于具有不同大小的图像。amol的答案很有效。我想不用JavaScript就可以了。对不起。没有具体说明。很高兴你找到了你想要的答案。不过,我的也行。我测试过了!文本中可能没有指定它,但JavaScript或jQuery没有标记:)
 <script type="text/javascript">
 function resizeHeight(){
 var resizedImage = document.getElementById('foo');
 resizedImage.style.height = (resizedImage.style.height * 200)/resizedImage.style.width;
 resizedImage.style.width = '200px';
 }
 </script>
 <img id="foo" src="foo.png" onload="resizeHeight()">