图片超过母体大小
问题描述:
我想中心和限制的图像
我有一个外container
并且具有display: inline-block;
一个image-container
具有的大小与图像(需要,将包含可拖动的项目)
相同但图像保持超过height: 100%;
有一种解决方法,以获得期望的结果(如截图) 图片超过母体大小
.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>
答
我最终使用的image-container
绝对定位其倒闭给孩子的大小。这需要父容器上的position: relative
。 overflow: hidden
在此处添加以解决由于image-container
转换造成的轻微偏移。
.container {
width: 300px;
height: 100px;
background: red;
position: relative;
overflow: hidden;
}
position
,top
,left
,和transform
这里设置为垂直和水平方向居中image-container
在父容器。
.image-container {
background: green;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
max-width
和max-height
需要匹配父容器的宽度和高度。
.main-image {
max-width: 300px;
max-height: 100px;
}
答
你可以这样说:
.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>
@tiborK响应速度......你可以把任何图像的容器内,如果它的响应。 – VXp
这是一个包含图像和一些可拖动项目的设计面板。它应该适用于各种屏幕尺寸,因此“奇怪”的场景 – UnLoCo