css - 图片超出父尺寸

标签 css image height

我想居中和限制图像
我有一个外部 container 和一个 image-container 其中有 display: inline-block; 与图像具有相同的大小(必需,将包含可拖动的元素)
但是图片一直超过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

最佳答案

我最终在 image-container 上使用绝对定位将其折叠为 child 的大小。这需要父容器上的 position: relativeoverflow: hidden 添加到此处以修复由于 image-container 上的转换导致的轻微偏移。

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

positiontoplefttransform 在这里设置为 image-容器垂直和水平放置在父容器中。

.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

关于css - 图片超出父尺寸,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47360242/

相关文章:

jquery - 选框跨度/跨度内容

css - images/css/js 等静态文件的相对路径

jquery - chrome 不返回正确的 .height()

html - 如何使我的标题图像以全高显示而不向其中的元素添加填充?

html - CSS 变换 - 旋转超过 -180 度时图像消失

html - 鼠标移开后的悬停效果

c# - 在 .net 中使用 System.Drawing 创建验证码

iphone - 如何生成具有圆角和阴影的 ImageView ?

html - 哪些 CSS 属性会影响 "height"属性值?

html - IE Flexbox justify-content center 溢出问题