【问题标题】:Make an image shrink to available height without expanding its parent使图像缩小到可用高度而不扩展其父级
【发布时间】:2018-03-24 17:34:47
【问题描述】:

我正在尝试创建一个包含两列的部分:

  1. 列的宽度相同(响应式)
  2. 块的高度由左列中包含的图像在拉伸到其父级的 100% 后的高度定义。
  3. 在右栏中有几个元素,其中一个是包含图像的链接。

我希望与最后一段中的图像的链接在图像具有纵向方向时缩小包含原始图像纵横比的高度而不拉伸它的容器。

不确定是否可以使用纯 CSS。尝试使用 flexbox 和网格布局,但我一定遗漏了一些东西。

我准备了一个小提琴:https://jsfiddle.net/Kuznets/8u6c70ku/3/

* { box-sizing: border-box }
.wrap { max-width: 80%; margin: 0 auto; }
.container { display: flex; }
.left, .right { 
  flex: 0 0 50%; 
  border: 1px solid black;
}
.left {
  position: relative;
  display: flex;
  align-items: flex-end;
}
.left div.left-text {
  position: absolute;  
  color: white;
  padding: 1em;
  font-size: 200%;
}
.should-set-height {
  width: 100%;
}

.right {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content:space-between;
}
<div class="wrap">
  <div class="container">
    <div class="left">
      <img class="should-set-height" src="https://dummyimage.com/200x240/aaaaaa/ffffff" alt="">
      <div class="left-text">
        This is a beautiful slogan
      </div>
    </div><!--/.left-->
    <div class="right">
      <header>Product title</header>
      <a class="fit-height" href="javascript:void(0)">
        <img class="should-shrink" src="https://dummyimage.com/200x400/aaaaaa/ffffff">
      </a>
      <div class="price">$ 19.99</div>
      <button class="button-black">Add to basket</button>    
    </div><!--/.right-->
  </div><!--/.containter-->
</div><!--/.wrap-->

【问题讨论】:

    标签: css responsive-design flexbox


    【解决方案1】:

    实现此目的的一种方法是将左侧图像设置为 width: 100%, height: auto;,然后为右侧容器使用背景图像。

    这是 CodePen 的快速演示:https://codepen.io/patriziosotgiu/pen/NaBmZe?editors=1100

    您还可以添加额外的规则,例如为左列添加min-width,或者让这些列适合移动设备的一列。

    注意:我假设左图大于 200x240px

    【讨论】:

    • 感谢您的意见。我没有想到这个想法。看起来如果没有 JavaScript,我将无法实现响应性(为移动/桌面加载不同尺寸的图像)。但它是一种选择。
    • 不客气。可能还有其他使用断点的方法。你能再给我几个要求吗?左图的最大尺寸是多少?比例总是相同,还是使用不同的图像尺寸?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-22
    • 2023-01-18
    • 1970-01-01
    • 1970-01-01
    • 2020-01-05
    • 2019-12-27
    相关资源
    最近更新 更多