我想居中和限制图像
我有一个外部 container
和一个 image-container
其中有 display: inline-block;
与图像具有相同的大小(必需,将包含可拖动的元素)
但是图片一直超过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
上使用绝对定位将其折叠为 child 的大小。这需要父容器上的 position: relative
。 overflow: hidden
添加到此处以修复由于 image-container
上的转换导致的轻微偏移。
.container {
width: 300px;
height: 100px;
background: red;
position: relative;
overflow: hidden;
}
position
、top
、left
和 transform
在这里设置为 image-容器
垂直和水平放置在父容器中。
.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;
}
关于css - 图片超出父尺寸,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47360242/