图片超过母体大小

问题描述:

我想中心和限制的图像
我有一个外container并且具有display: inline-block;一个image-container具有的大小与图像(需要,将包含可拖动的项目)
相同但图像保持超过height: 100%;
有一种解决方法,以获得期望的结果(如截图) enter image description here图片超过母体大小

.container { 
 
    width: 300px; 
 
    height: 100px; 
 
    background: red; 
 
    text-align: center; 
 
} 
 

 
.image-container { 
 
    display: inline-block; 
 
    background: #0f0; 
 
    outline: 5px solid #00f; 
 
    max-width: 100%; 
 
    max-height: 100%; 
 
    
 
} 
 

 
.main-image { 
 
    max-width: 100%; 
 
    max-height: 100%; 
 
}
<div class="container"> 
 
    <div class="image-container"> 
 
    <img class="main-image" src="http://via.placeholder.com/400x400" /> 
 
    </div> 
 
</div>

fiddle

+0

@tiborK响应速度......你可以把任何图像的容器内,如果它的响应。 – VXp

+0

这是一个包含图像和一些可拖动项目的设计面板。它应该适用于各种屏幕尺寸,因此“奇怪”的场景 – UnLoCo

我最终使用的image-container绝对定位其倒闭给孩子的大小。这需要父容器上的position: relativeoverflow: hidden在此处添加以解决由于image-container转换造成的轻微偏移。

.container { 
    width: 300px; 
    height: 100px; 
    background: red; 
    position: relative; 
    overflow: hidden; 
} 

positiontopleft,和transform这里设置为垂直和水平方向居中image-container在父容器。

.image-container { 
    background: green; 
    position: absolute; 
    top: 50%; 
    left: 50%; 
    transform: translate(-50%, -50%); 
} 

max-widthmax-height需要匹配父容器的宽度和高度。

.main-image { 
    max-width: 300px; 
    max-height: 100px; 
} 

fiddle

+0

我希望'image-container'具有与图像相同的尺寸。这是因为它将包含可拖动的元素,我必须保存它们的位置而不处理偏移量。我现在猜测这是不可能的 – UnLoCo

+0

对不起,错过了你的问题的条款 – Potter

+0

谢谢,我应该强调它 – UnLoCo

你可以这样说:

.container { 
 
    width: 300px; 
 
    height: 100px; 
 
    background: red; 
 
    display: flex; 
 
} 
 

 
.image-container { 
 
    display: flex; 
 
    justify-content: center; /* horizontal centering */ 
 
    background: #0f0; 
 
    outline: 5px solid #00f; 
 
} 
 

 
img { /* responsiveness */ 
 
    display: block; 
 
    width: auto; 
 
    height: auto; 
 
    max-width: 100%; 
 
    max-height: 100%; 
 
}
<div class="container"> 
 
    <div class="image-container"> 
 
    <img class="main-image" src="http://via.placeholder.com/400x400"> 
 
    </div> 
 
</div>