【问题标题】:Image exceeding parent size超过父尺寸的图像
【发布时间】:2017-11-18 07:58:34
【问题描述】:

我想居中并限制图像
我有一个外部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>

fiddle

【问题讨论】:

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

标签: css image height


【解决方案1】:

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

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

positiontoplefttransform 在此处设置为使 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

【讨论】:

  • 我希望image-container 具有与图像相同的大小。那是因为它将包含可拖动元素,我必须在不处理偏移量的情况下保存它们的位置。我现在猜这是不可能的
  • 对不起,错过了你的问题的那个子句
  • 谢谢,我应该强调一下
  • 试试这个:它并不完美,但它真的很接近:jsfiddle.net/j32wb3nL/21
  • 我可能会使用您的解决方案并使用一些 js 使其动态化。请编辑您的答案,我会接受它:)
【解决方案2】:

你可以这样做:

.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>

【讨论】:

    猜你喜欢
    • 2013-02-24
    • 2017-03-21
    • 1970-01-01
    • 2013-02-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-28
    相关资源
    最近更新 更多