简体   繁体   English

如何将图像放入具有非固定高度的容器中?

[英]How to fit an image inside a container with non-fixed height?

 #myDiv { display: inline-block; border:1px solid red; width:200px; } #myImg { max-height:100%; max-width:100%; } #anotherDiv { display:inline-block; border:1px solid blue; height:100px; width:50px; }
 <div id="myDiv"> <img src='https://i.imgur.com/rw9ypWD.png' id="myImg"> <div id="anotherDiv"> </div> </div>

I want to fit the image height to its container div.我想将图像高度适合其容器 div。

Using height:100%;使用height:100%; works only when the container have a fixed height.仅当容器具有固定高度时才有效。

Simply add display:flex to container to get the stretch alignment by default:只需将display:flex添加到容器即可默认获得拉伸 alignment:

 #myDiv { display: inline-flex; border:1px solid red; width:200px; } #anotherDiv { display:inline-block; border:1px solid blue; height:100px; width:50px; }
 <div id="myDiv"> <img src='https://i.imgur.com/rw9ypWD.png' id="myImg"> <div id="anotherDiv"> </div> </div>

A different result with display:grid : display:grid的不同结果:

 #myDiv { display: inline-grid; grid-auto-flow:column; /* column flow */ justify-content: flex-start; /* align everything to left */ border:1px solid red; width:200px; } #myImg { height:100%; /* image 100% height of the div */ } #anotherDiv { display:inline-block; border:1px solid blue; height:100px; width:50px; }
 <div id="myDiv"> <img src='https://i.imgur.com/rw9ypWD.png' id="myImg"> <div id="anotherDiv"> </div> </div> <div id="myDiv"> <img src='https://i.imgur.com/rw9ypWD.png' id="myImg"> <div id="anotherDiv" style="height:50px"> </div> </div>

Here the another way without using flex: I will recommend that display:flex;这里是另一种不使用 flex 的方法:我会推荐display:flex; will be the good and easy one.将是一个好的和容易的。

 #myDiv { display: inline-block; border: 1px solid red; width: 200px; position: relative; padding-left: 22px; } #myImg { position: absolute; left: 0; height: 100%; } #anotherDiv { display: inline-block; border: 1px solid blue; height: 100px; width: 50px; }
 <div id="myDiv"> <img src="https://i.imgur.com/rw9ypWD.png" id="myImg" /> <div id="anotherDiv"></div> </div>

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

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