【问题标题】:Scale flex box height to fit image div缩放弹性框高度以适合图像 div
【发布时间】:2019-11-25 16:36:14
【问题描述】:

我正在构建一条聊天消息,我想在文本气泡中放置一张图片。气泡具有固定宽度,应根据图像纵横比缩放其高度。

我无法缩放 div 以保持 img 的纵横比。找到的所有答案都使用 <img> 标签,而我使用的是 div 并且没有一个解决我的问题。

这是期望的结果:

我所取得的结果要么是非常小的img(如果我不施加任何垂直或水平尺寸,则为空对话气泡的大小)或长的img,如果我施加宽度并保持高度动态.

.speech-right-wrapper {
  max-width: 90%;
  display: flex;
  flex-direction: column;
}

speech-right-message-container {
  display: flex;
  justify-content: flex-end;
  align-items: flex-start;
}

.speech-right-bubble {
  position: relative;
  background: rgb(154, 226, 255);
  box-shadow: 0px 1px 2px gray;
  border-radius: 15px 0 15px 15px;
  display: flex;
}

.bubble-background {
  width: 200px;
  height: auto;
  overflow: hidden;
}

.bubble-background-img {
  position: absolute;
  border-radius: 15px 0 15px 15px;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  overflow: hidden;
  background: no-repeat;
  background-size: cover;
  background-position: center;
}
<div class="speech-right-wrapper">
  <div class="speech-right-message-container">
    ...
    <div class="speech-right-bubble">
      <div class="bubble-background">
        <div class="bubble-background-img" v-bind:style="{ 'background-image': 'url(' + require('../assets/img/profiles/' + storyPath + bubble.bubble_background) + ')' }" v-bind:alt="bubble.bubble_background"></div>
      </div>
      ...
    </div>
    ...
  </div>
</div>

更新

为了清楚起见,我需要将&lt;div class="bubble-background-img"&gt; 的宽度固定(比如200px)和height: auto 以保持图像纵横比;我需要 &lt;div class="speech-right-bubble"&gt; 缩放以适应里面的图像。

另外,不幸的是我需要使用&lt;div&gt; 标签,因为v-bind:src 似乎不适用于本地图像。如果我这样做:

<img class="bubble-background-img" v-bind:src="'../assets/img/profiles/' + storyPath + bubble.bubble_background"/>

我明白了:

【问题讨论】:

  • 如果您可以使用codepenjsfiddle 为您的应用创建一个分支,将会更容易
  • 你不能使用&lt;img&gt;标签还是说你看到的使用&lt;img&gt;标签的解决方案不起作用?
  • @Dadboz,我不能分享完整的代码。
  • @Victor,该应用程序在 Vue 中,我无法使用 img 标签渲染图像。经过多次尝试,我发现 'v-bind:style' 和 'require' 可以正常工作。
  • v-bind:src 不适用于您的 url 变量?

标签: html css vue.js flexbox


【解决方案1】:

您可能应该找到解决 v-bind:src 问题的方法,因为显示内容图像的正确方法是通过 HTML img 元素。

也就是说,有一个解决方案,但它依赖于使用 CSS content 属性进行元素替换,这是一项相当新的技术,Microsoft Edge 显然仍然不支持。下面的 CSS 代码是它的要点,在 Firefox 68 中对我有用:

div { content: ('image.jpeg'); max-width: 200px; }

(理论上,这种技术的一种变体也应该适用于向后兼容的 CSS ::before::after 伪元素,但在我的测试中,图像莫名其妙地无法缩放。我没有花费很多时间都在尝试。)

【讨论】:

  • 简洁的解决方案,并且对元素替换的支持并不像我预期的那样零散!
【解决方案2】:

我不是百分百确定你想要什么,但你可以尝试将背景大小设置为百分比?

background-size: 100%;
background-position: center center;

在背景大小中使用百分比可让您根据父容器缩放一个或多个轴。 (例如,background-size: 100% 100%; 将缩放宽度和高度,并产生与 contain 值等效的效果。

这行得通吗?

(就我个人而言,我会使用元素加载图像,因为这就是它们的用途,您可以酌情使用object-fit,但显然取决于您如何构建视图...)

【讨论】:

  • 艾伦,我的解释可能不太清楚:我需要图片为 200px 宽和height: auto 以保持自己的纵横比。我需要父 div class="speech-right-bubble" 来缩放它的尺寸以适应里面的图像。
猜你喜欢
  • 2013-11-05
  • 2015-07-14
  • 2019-09-13
  • 2012-04-17
  • 1970-01-01
  • 2019-09-01
  • 2016-05-10
  • 2023-03-16
  • 1970-01-01
相关资源
最近更新 更多