如何将div大小调整为图像显示大小

如何将div大小调整为图像显示大小

问题描述:

我有一个div内的图像。 div具有固定的高度,低于图像的内在高度。 我希望div的宽度始终等于图像的“显示”宽度(这是未知div的高度和图像的高度/宽度比的函数)。如何将div大小调整为图像显示大小

Here is a codepen example of what I want to do (having "shrink" and "other" divs the same width than their child image)

<div class="container"> 
    <div class="shrink"> 
     <img src="https://dummyimage.com/600x400/0f0/fff" /> 
    </div> 
    <div class="other"> 
    <img src="https://dummyimage.com/600x400/00f/fff" /> 
    </div> 
</div> 

div { margin: 5px; } 
img { max-height: 100%; } 
.container { 
    background-color: red; 
    display: flex; 
    flex-flow: row nowrap; 
    width: 800px; 
    height: 100px; 
    overflow: hidden; 
} 
.shrink { 
    flex: 0 1 auto; 
    background-color: #88FF88; 
} 
.other { 
    flex: 0 1 auto; 
    background-color: #8888FF; 
} 

是否有可能只用HTML/CSS即没有使用Javascript?

在此先感谢。

+0

这样的事情? http://codepen.io/anon/pen/BLAZjJ – DaniP

删除宽度作为您的容器的属性,div将符合其内容的宽度。

这是否适合您?

+0

我不希望“容器”div符合其内容的宽度。我想要这个“缩水”和“其他”divs的行为。 – jay