简体   繁体   English

CSS - 如何使图像容器宽度固定,高度自动拉伸

[英]CSS - how to make image container width fixed and height auto stretched

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. 我想做的是使用div的宽度制作img显示并拉伸它的高度。 I also want the div stretch itself to fit the img. 我也希望div伸展自己适合img。 Is that possible? 那可能吗?

What you're looking for is min-height and max-height . 你要找的是min-heightmax-height

img {
    max-width: 100%;
    height: auto;
}

.item {
    width: 120px;
    min-height: 120px;
    max-height: auto;
    float: left;
    margin: 3px;
    padding: 3px;
}

Try width:inherit to make the image take the width of it's container <div> . 尝试width:inherit使图像占据容器<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. 不要在<div>设置高度,它的大小将适合图像高度。

img {
    width:inherit;
}

.item {
    border:1px solid pink;
    width: 120px;
    float: left;
    margin: 3px;
    padding: 3px;
}

JSFiddle example JSFiddle示例

No, you can't make the img stretch to fit the div and simultaneously achieve the inverse. 不,你不能使img拉伸以适应div并同时实现逆。 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. 但是,您可以从其他答案中获取一些注释并实现一些最小和最大尺寸,但这不是问题。

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. 使用此块告诉我您希望图像大小可变,因此父div是图像缩放的宽度。 height: auto is going to keep your image aspect ratio in tact. height: auto将保持您的图像宽高比。 if you want to stretch the height it needs to be 100% like this fiddle. 如果你想伸展高度,它需要100%喜欢这个小提琴。

img {
    width: 100%;
    height: auto;
}

http://jsfiddle.net/D8uUd/1/ http://jsfiddle.net/D8uUd/1/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM