Adjust the flex box height to match the dimensions of the image container

Currently, I am in the process of constructing a chat message layout and I am facing a challenge where I need to incorporate an image within a text bubble. The width of the bubble is fixed, but the height should adjust based on the aspect ratio of the image.

Despite my efforts, I have been unable to resize the div to maintain the image's aspect ratio. Most of the solutions I've come across involve using an <img> tag, but in my case, I am working with a div and have not been successful in resolving this issue.

Here is the desired outcome I am aiming for:

https://i.sstatic.net/0Ic6G.png

https://i.sstatic.net/cZs8K.png

However, the result I have achieved so far is either a tiny img (comparable to an empty speech bubble when no vertical or horizontal dimensions are imposed) or an elongated img when I set the width and leave the height flexible.

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

UPDATE

To clarify, I require the

<div class="bubble-background-img">
to have a fixed width (e.g., 200px) and height: auto to preserve the image aspect ratio. Additionally, I need the
<div class="speech-right-bubble">
to adjust its size to accommodate the image.

Unfortunately, I am obliged to use a <div> tag, as v-bind:src does not seem to work for local images. When I attempt the following:

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

I encounter this issue: https://i.sstatic.net/vbFZB.png

Answer №1

In order to address the issue with your v-bind:src, it would be advisable to seek an alternative solution since the proper method of displaying a content image is by utilizing the HTML img element.

However, there is a workaround available that involves leveraging the CSS content property for replacing elements. This approach is a relatively new technology that may not be fully supported in Microsoft Edge. Below is a snippet of CSS code that successfully functioned in my testing on Firefox 68:

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

It's worth noting that a modified version of this method could potentially be compatible with the CSS ::before and ::after pseudo-elements, though I encountered difficulty with image scaling in my trials. However, I didn't conduct extensive experimentation with this aspect.

Answer №2

I'm not entirely confident in understanding your objective, but have you considered setting the background-size as a percentage?

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

Utilizing a percentage in the background size property allows you to adjust one or more axis based on the parent container. For example, background-size: 100% 100%; would scale both width and height, creating an effect similar to the contain value).

Do you think that suggestion would be effective for your needs?

(From my perspective, I prefer loading images using an img element as it serves that specific purpose, and you could utilize object-fit as needed. However, this approach may vary depending on your view architecture...)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilizing a dropdown feature in Bootstrap for creating X columns of lists instead of a traditional single list

Check out my Fiddle. Beneath Dropdown1 lies a single-column list of actions. I'm looking to expand this list across multiple columns, like 5 or the width of the page. I'm hoping there's a Bootstrap CSS class I can use for this, but I migh ...

Enhance User Experience with a Responsive Website Dropdown Menu

Currently, I am focused on enhancing the responsiveness of my website and I realized that having a well-designed menu for mobile view is essential. To address this need, I added a button that only appears when the screen size is 480px or lower, which seems ...

Real-Time Chat Update Script

Recently, I've been delving into PHP and attempting to create a live chat web application. The data for the chat is stored in a MySQL database, and I have written a function called UpdateDb() that refreshes the chat content displayed in a certain div ...

Is it advisable to adjust the type of input control according to the drop down choice made?

I am currently working on creating an edit screen for users to update rows of data. One of the fields is a dropdown menu, while another field is an input labeled 'value'. Depending on the selection in the dropdown menu, I need to display differen ...

What is the best way to retrieve an array of objects from Firebase?

I am looking to retrieve an array of objects containing sources from Firebase, organized by category. The structure of my Firebase data is as follows: view image here Each authenticated user has their own array of sources with security rules for the datab ...

The peculiar formatting issue with the jQuery datepicker that arises when adding more months

When adjusting the numberOfMonths parameter to a higher value such as 6, I noticed that the datepicker display appears unusual with the background extending further than expected. Take a look at my demonstration on jsfiddle: http://jsfiddle.net/zw3z2vjh/ ...

Guide on darkening the surrounding div of an alert to give it a modal-like effect

I want to display an alert to the user in a visually appealing way. To achieve this, I am utilizing Bootstrap's alert class. Here is how I am showing the user a div: <div class="alert alert-warning alert-dismissible" role="alert"> Some text ...

Guide to embedding CSS into a DOC file generated from HTML with PHP

I've created a document, but it's not linking to the external CSS file. I have added .css files in my code, but when I generate the document, it doesn't apply the CSS classes. Here is my code: <?php header("Content-type: application/vn ...

Display detailed information in InfoWindows when markers on a Vue Google Map are clicked

I'm working on creating a map similar to Airbnb's design. Each location marker displays the rental price, and when clicked, a popup with more details appears. However, I'm facing an issue where clicking any marker only shows the details of ...

What could be causing my bootstrap-switch to malfunction?

Here is the snippet of code I am working with: jQuery.each($('.onoffswitch-checkbox'), function(i, slotData) { console.log($(slotData).bootstrapSwitch('state')) }) <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1 ...

Table featuring identical submit buttons in each row: initial submit button is nonfunctional (potential issue with multiple identical IDs)

My table displays product files, with the option to add notes. If a note is added, it shows in a row. If not, a text area field with a submit button appears instead. Everything seems to be working well, except for the first row without a note. After addin ...

What is the method for retrieving a module from a store using its name represented as a string?

Just starting out with Vuejs and encountering a slight hiccup. I want to utilize a store, however, all I have is the name stored as a string. From what I understand, I can access the method (all()) of the store by using: storeName.all My issue lies in ha ...

Guide to ensuring the navbar remains at the top of the webpage following an image

I am attempting to create a sticky navbar that stays at the top of the page once the header has been scrolled past. It should have a similar effect as shown in this example on codepen.io, but with the addition of an image that stretches across most of the ...

JavaScript's data.map function cannot be found

I've been developing a full stack application using Vue.Js, NodeJS, ExpressJS, and MongoDB. In my frontend code, I have a PostService.js class that manages HTTP requests to the API. However, I encountered an issue while trying to map the response data ...

Using query strings to manipulate the URL of an iframe and add additional information

I am facing a challenge with integrating my legacy perl application into an MVC application. I have set up a structure where the legacy application is loaded into an iframe within default.aspx, but I need to capture the URL of each page within the iframe a ...

Top method for transitioning FontAwsome stars class from regular to solid

How can I dynamically change the class of 5 stars of FontAwesome Icons from regular to solid based on a numeric variable level that ranges from 0 to 5? <template> <div id="five-stars"> <font-awesome-icon v-for="(inde ...

Utilize API or alternative methods for analyzing Instagram data

My master's thesis requires me to dissect multiple Instagram profiles, each containing over 1000 posts. I am in need of a comprehensive list including the following details: Type of Post (Image, Multi Image, Video) Description Likes Comments (total c ...

Adjust the container width to match the width of the visible thumbnails?

Take a look at my website over at: . If you want to see more thumbnails, consider switching to a different album. The album titled Paris contains the most images. If you press the "Show Photo Grid" button located in the bottom-right corner, you'll be ...

Transmitting HTML through a Java socket connection

I am facing an issue where I am attempting to send the code from 'index.html' using Java socket wrapped in BufferedWriter. However, when I try to connect to 'localhost:port' in a browser, I encounter different results: text output (&l ...

What is the best way to vertically align a two-line nav item?

I am looking to design a navigation menu with items that can accommodate one or two lines of text. https://i.sstatic.net/nkxRL.png The items should have consistent height and the text should be vertically centered. Additionally, I want the entire box to ...