【问题标题】:Fit image in div which have more height than image在高度比图像高的 div 中适合图像
【发布时间】:2016-01-20 18:44:37
【问题描述】:

我的图像的高度比我想要的 div 低。 div 的宽度是固定的。 div 的高度不固定它的动态。 如何实现这一点。我试过css 最大宽度:100%; 最大高度:100%; 但它不起作用。

【问题讨论】:

  • 我假设您希望图像填充整个 div,而不会扭曲图像。如果这是真的,您是否希望 DIV 的高度与图像高度匹配,或者您是否希望图像变大以匹配 div,从而切断图像的一部分?
  • 请包含不起作用的 html 和 css 文件以及您想要的内容的 scetchup :)
  • 我有两个并排的 div,右边的 div 包含一些没有固定高度的文本。左 div 包含图像,我希望图像采用右 div 的高度。
  • 您想缩放图像以使其具有与不同元素完全相同的高度吗?嗯,Javascript。

标签: html css


【解决方案1】:

您可以只使用 css 来做到这一点,方法是将左侧 div 和图像位置设为绝对值,并使其适合容器的高度,该容器的高度将由右侧 div 中的内容决定。

<div class="outer">
  <div class="left">
    <img src="source.jpg"/>
  </div>
  <div class="right">
    Content which will determine height of both divs
  </div>
</div>

<style>
  .outer {
    position: relative;
  }

  .left {
    position: absolute;
    top: 0;
    bottom: 0;
    width: 50%
  }

  .left img {
    position: absolute;
    top: 0;
    bottom: 0;
  }

  .right {
    margin-left: 50%;
  }
</style>

【讨论】:

    【解决方案2】:

    您可以使用 CSS 属性 object-fit (Current browser support)

    只需在 img 上设置object-fit: cover;

    来自MDN

    封面

    被替换的内容的大小可以保持其纵横比,同时 填充元素的整个内容框:它的具体对象大小是 解决为针对元素使用的宽度的覆盖约束和 高度。

    Codepen demo

    【讨论】:

      猜你喜欢
      • 2014-06-05
      • 1970-01-01
      • 1970-01-01
      • 2019-11-25
      • 2016-01-27
      • 2018-07-25
      • 1970-01-01
      • 2015-02-21
      • 1970-01-01
      相关资源
      最近更新 更多