Html CSS - 如何使图像容器宽度固定并自动拉伸高度
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15300059/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
CSS - how to make image container width fixed and height auto stretched
提问by user2142709
I've go some html code like this:
我有一些这样的html代码:
<div class="item">
<img src="...">
</div>
And css code like this:
和 css 代码是这样的:
img {
max-width: 100%;
height: auto;
}
.item {
width: 120px;
height: 120px;
height: auto;
float: left;
margin: 3px;
padding: 3px;
}
What I would like to do is to make the img display using the div's width and stretch its height. I also want the div stretch itself to fit the img. Is that possible?
我想要做的是使用 div 的宽度制作 img 显示并拉伸其高度。我还希望 div 拉伸本身以适合 img。那可能吗?
回答by Ryan
What you're looking for is min-height
and max-height
.
你要找的是min-height
和max-height
。
img {
max-width: 100%;
height: auto;
}
.item {
width: 120px;
min-height: 120px;
max-height: auto;
float: left;
margin: 3px;
padding: 3px;
}
回答by jim31415
Try width:inherit
to make the image take the width of it's container <div>
. It will stretch/shrink it's height to maintain proportion. Don't set the height in the <div>
, it will size to fit the image height.
尝试width:inherit
使图像占据其容器的宽度<div>
。它会拉伸/收缩它的高度以保持比例。不要在 中设置高度<div>
,它会调整大小以适应图像高度。
img {
width:inherit;
}
.item {
border:1px solid pink;
width: 120px;
float: left;
margin: 3px;
padding: 3px;
}
回答by Dylan Valade
No, you can't make the img stretch to fit the div and simultaneously achieve the inverse. You would have an infinite resizing loop. However, you could take some notes from other answers and implement some min and max dimensions but that wasn't the question.
不,您不能使 img 拉伸以适应 div 并同时实现反向。你会有一个无限的调整大小循环。但是,您可以从其他答案中做一些笔记并实现一些最小和最大尺寸,但这不是问题。
You need to decide if your image will scale to fit its parent or if you want the div to expand to fit its child img.
您需要决定您的图像是否会缩放以适合其父级,或者是否希望 div 扩展以适合其子级 img。
Using this block tells me you want the image size to be variable so the parent div is the width an image scales to. height: auto
is going to keep your image aspect ratio in tact. if you want to stretch the height it needs to be 100%
like this fiddle.
使用此块告诉我您希望图像大小可变,因此父 div 是图像缩放到的宽度。 height: auto
将保持您的图像纵横比机智。如果你想拉伸高度,它需要100%
像这个小提琴。
img {
width: 100%;
height: auto;
}