Utilizing the Flex property on the parent div ensures that all child elements receive an equal width

I am currently working on a messaging application and I want the layout to be similar to Twitter or Whatsapp. Specifically, I want the messages from the person the user is chatting with to appear on the left side, while the user's own messages should be on the right side.

Below is the React JSX markup that I have so far:

<div
    style={{
      overflow: "auto",
      display:"flex",
      flexDirection:"column",
    }}
>
    {chatMessageInfo[currentChatID].map((e, idx) => (
        <>
            {e.data.sender === ourRef ? (
                <div className="ourMessage">
                    <p>{e.data.msg.text}</p>
                </div>
            ) : (
                <div className="theirMessage">
                    <p>{e.data.msg.text}</p>
                </div>
            )}
        </>
    ))}
</div>

Here is the corresponding CSS:

.ourMessage {
    display: flex;
    border-radius: 0px;
    margin-top: 0px;
    margin-bottom: 0px;
    max-width: 300px;
    background: rgb(29 155 240);
    border-radius: 25px;
    padding-left: 10px;
    padding-right: 10px;
    margin-left: 500px;
    text-align: right;
    float: right;
    zoom: 1;
}

.theirMessage {
    display: flex;
    border-radius: 0px;
    margin-top: 0px;
    margin-bottom: 0px;
    max-width: 300px;
    background: rgb(150, 150, 150);
    border-radius: 25px;
    padding-left: 10px;
    padding-right: 10px;
    text-align: left;
    float: left;
    zoom: 1;
}

Currently, everything works well in terms of alignment using floats. However, when I add display:"flex" to the parent div, all the message divs somehow end up with the same width. https://i.sstatic.net/BFHx6.png

If anyone has any suggestions on how to resolve this issue, please share them. Just for context, I am developing this project using NextJS as a metaframework alongside React.

Answer №1

If you're working with CSS, you have the option to apply 'fit content' for setting the width of individual div elements

.ourMessage, .theirMessage {
   width: fit-content;
}

By doing this, each div's width will automatically adjust to accommodate its content

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

Encountering a dilemma during the docker build process with npm install is frustrating, especially when faced with an error message like: "Invalid response body when attempting

Encountering a docker build issue with npm install that seems to only occur inside the docker environment. The process works perfectly on my operating system Error Step 6/8 : RUN npm cache clear --force && npm install --legacy-peer-deps ---> ...

Retrieving the `top` value using `$this.css("top") can either return an object or an element value

Something odd is happening with my HTML object: <div data-x="1" data-y="1" class="tile empty" style="top: 32px; left: 434px;"> <div class="inner">1:1</div> </div> When attempting to access its top property in jQuery using the ...

What is the best way to upload a file to a server while working with Vue.js in the Filemanager plugin, or how can I access a global function

How can I upload a file to the server using Vue.js in the Filemanager plugin? I have tried multiple methods and the console log shows that the upload was successful, but I am not able to see any files on the server. Does anyone know what could be wrong? & ...

Accessing an external webpage within a React.js application while maintaining visibility of the navbar

Seeking assistance on how to open an external link within a React app below the navbar when navigating to "/WebSite". Currently using react router for page navigation. Here's the code snippet: const App = () => { return( <BrowserRouter&g ...

Tips for customizing the cursor to avoid it reverting to the conventional scroll cursor when using the middle click

When you wish to navigate by scrolling with the middle mouse button instead of using the scroll wheel, simply middle-click and your cursor will change allowing for easy scrolling on web pages. Even though I am utilizing style="cursor: pointer" and @click. ...

Guide on how to navigate users to a new page using react-router-dom v6 within a class-based component

I am facing an issue where I need to redirect the user to '/dashboard' after logging in, but I do not want to use history.push() from react-router-dom v5.2.0 as I have react-router-dom v6 installed. Is there another alternative to achieve this re ...

What is the best way to place a 3D model at random points on the surface of a sphere while ensuring that it always faces the right direction?

I'm faced with the challenge of placing huts randomly on a spherical world. While this task is feasible, the issue arises when the huts do not sit correctly - their bottom should be in contact with the tile below. I've experimented with the &apos ...

Unable to add chosen elements to array - Angular material mat select allowing multiple selections

Can anyone assist me in figuring out what I am doing wrong when attempting to push data to an empty array? I am trying to only add selected values (i.e. those with checked as true), but I can't seem to get inside the loop This is the current conditi ...

Remove elements generated by the .after method with Jquery

In my HTML file, I have a table with hard-coded column headers: <table id="debugger-table"> <tr> <th>Attribute</th> <th>Computed</th> <th>Correct</th> </tr> </table&g ...

Tips for preventing my text from disappearing off the screen when I resize it

Hello there and thanks in advance. I've recently delved into the world of HTML and CSS and I'm currently in the process of building my own website. I've encountered an issue with a div container where I'm utilizing Bootstrap elements. T ...

Achieving full-width container on mobile devices with Bootstrap

Despite my efforts in the CSS file, I am still struggling to get the container to take up the full width on mobile devices. Here is my CSS code: @media (max-device-width: 1024px) { .col-sm-2{ width: 100%; } .container { margin: 0 auto; width: ...

Using the Trigger Method in a Vue JS Component with Sibling Components

Seeking assistance once again for a VueJS2 project. Currently, I have a setup with a parent component, along with child1 and child2. The scenario is that the form in child1 needs to receive data from child2, which acts as a table. When a checkbox on a row ...

Resetting a form in React JS: A step-by-step guide

How can I clear the input values in a React JS form upon clicking Reset? class AddFriendForm extends Component { constructor(props) { super(props) this.state = { firstname: '', lastname: '', } } render() { c ...

ReactJS - When a child component's onClick event triggers a parent method, the scope of the parent method may not behave as anticipated

In my current setup, I have a parent component and a child component. The parent component contains a method within its class that needs to be triggered when the child component is clicked. This particular method is responsible for updating the store. Howe ...

Toggle the current list item in Jquery to expand to 100% width, while simultaneously shifting any adjacent items on the left and right downwards if present

I am working with a list (ul) that contains multiple items displayed in a tiled format. Each item has a brief introduction and can expand to show more information when clicked on. What I would like to achieve is for the expanded item to take up the entire ...

Exploring the wilderness: Safari with a twist of negative margin

Dealing with two values, "price" and "old price". When displaying the "old price", I need to cross it out with a line that is thinner than the default text-decoration: line-through. Below is the code snippet: HTML: <span class="price"> <span c ...

Utilizing JSON data to populate a modal window in HTML

How can I incorporate JSON data into an HTML modal window? I have a set of 12 buttons, and when a user clicks on one, I want to display the corresponding month's information from a JSON file. let myJson; $(`button`).on(`click`, function() { let ...

Unable to see my Vue component within Laravel

My Vue component is not appearing on the screen and I am unable to identify the issue. I have checked my console for errors and I am using npm run hot Here is my app.js file: require('./bootstrap'); window.Vue = require('vue').default ...

Styling a custom Qt class using a CSS selector

I have developed a custom "Slider" widget as a subclass of QWidget and am looking to customize its appearance using Qt's stylesheets. Is there a way to define this widget to the Qt application so that any styling set in the application stylesheet will ...

Uploading Files within Angular FormArray

I am facing an issue with my formArray which contains file upload inputs in each element. Whenever I upload an image in one input, it changes the values of other file inputs in different rows. https://i.stack.imgur.com/3haZW.png Current Behavior: Uploadi ...