缩放伸缩框高度以适合图像div

时间:2019-07-16 21:35:57

标签: html css vue.js flexbox

我正在建立一个聊天消息,我想在文本提示框内放入一个图像。气泡的宽度固定,应根据图像的宽高比缩放高度。

我无法缩放div来保持img的宽高比。找到的所有答案都使用<img>标记,而我使用的是div,但这些都没有解决我的问题。

这是理想的结果:

enter image description here

enter image description here

我获得的结果不是很小的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>

更新

为清楚起见,我需要固定<div class="bubble-background-img">的宽度(例如200px)和height: auto来保持图像的长宽比;并且我需要<div class="speech-right-bubble">来缩放以适合内部图像。

此外,不幸的是,我需要使用<div>标记,因为v-bind:src似乎不适用于本地图像。如果我这样做:

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

我明白了:enter image description here

2 个答案:

答案 0 :(得分:1)

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

那是一个解决方案,但是它依赖于使用CSS content属性进行元素替换,这是一种相当新的技术,Microsoft Edge显然仍然不支持该技术。以下CSS代码是它的要旨,并为我在Firefox 68中的测试工作:

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

(从理论上讲,该技术的一种变体也应该与向后兼容的CSS ::before::after伪元素一起使用,但是在我的测试中图像无法按比例缩放。我却没有花很多时间进行实验。)

答案 1 :(得分:0)

我不确定您要做什么,但是您可以尝试将背景尺寸设置为百分比吗?

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

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

那行得通吗?

(个人而言,我会使用一个元素来加载图像,因为这正是它们的用途,您可以适当地使用object-fit,但显然取决于您如何构造视图...)< / p>

相关问题