What is the best way to dynamically adjust the width of a multiline paragraph element to eliminate excess white space?

Allow me to elaborate... I am constructing a visual representation of an SMS conversation using HTML. Here is the current setup:

@import url("https://fonts.googleapis.com/css2?family=Roboto:ital,wght@0,100;0,300;0,400;0,500;0,700;0,900;1,100;1,300;1,400;1,500;1,700;1,900&display=swap");

body {
    background-color: black;
    margin: 0;
    font-family: "Roboto", sans-serif;
    font-size: 2rem;
}

section {
    margin: 0 auto;
    background-color: white;
    max-width: 1080px;
    display: flex;
    flex-direction: column;
    padding: 20px;
}

article {
    display: inline-block;
    padding: 10px 20px;
    border-radius: 30px;
    width: fit-content;
    max-width: 75%;
}

article p {
    margin: 0;
    word-wrap: break-word;
}

article.them {
    color: black;
    background-color: lightgray;
    align-self: flex-start;
}

article.me {
    color: white;
    background-color: darkblue;
    align-self: flex-end;
}

/* Smaller margin between consecutive messages from the same sender */
article.me + article.me,
article.them + article.them {
    margin-top: 3px;
}

/* Standard margin between different senders */
article.me + article.them,
article.them + article.me {
    margin-top: 20px;
}
<body>
    <section>
        <article class="them">
            <p>Lorem ipsum, dolor sit amet.</p>
        </article>
        <article class="me">
            <p>Lorem ipsum.</p>
        </article>
        <article class="me">
            <p>
                Lorem ipsum dolor sit, amet consectetur adipisicing elit.
                Nostrum tempore excepturi dolore nam? Odio architecto
                tempora maiores corrupti nihil autem necessitatibus natus
                consequuntur adipisci hic nisi quaerat voluptate, incidunt
                beatae?
            </p>
        </article>
        <article class="them">
            <p>
                Lorem ipsum dolor sit amet consectetur adipisicing elit.
                Repellat officia delectus sequi quo quas!
            </p>
        </article>
    </section>
</body>

Single line text bubbles adjust width accordingly, but multiline bubbles always stretch to maximum width due to paragraph settings. Can CSS make paragraphs shrink in width for multiline bubbles and remove excess white space caused by line breaks?

Answer №1

Looking to dynamically shrink a multiline paragraph element horizontally and eliminate white space?

To achieve this, utilize the inline-block property for the article class, allowing text to adjust based on content while preventing it from exceeding the actual width.

Consider using max-width to control horizontal expansion, but be cautious of unnecessary vertical expansion caused by pre-wrap.

Avoid employing white-space: 'nowrap' unless aiming for single-line bubbles.

You can view the working output image here.

Below is the modified code:

CSS

@import url("https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500&display=swap");

        body {
            background-color: black;
            margin: 0;
            font-family: "Roboto", sans-serif;
            font-size: 2rem;
        }

        section {
            margin: 0 auto;
            background-color: white;
            max-width: 1080px;
            display: flex;
            flex-direction: column;
            padding: 20px;
        }

        article {
            display: inline-block;
            padding: 10px 20px;
            border-radius: 30px;
            width: auto;
            max-width: 75%;
            word-wrap: break-word;
        }

        article p {
            margin: 0;
            display: inline;
            white-space: normal;
        }

        article.them {
            color: black;
            background-color: lightgray;
            align-self: flex-start;
        }

        article.me {
            color: white;
            background-color: darkblue;
            align-self: flex-end;
        }

        article.me+article.me,
        article.them+article.them {
            margin-top: 3px;
        }

        article.me+article.them,
        article.them+article.me {
            margin-top: 20px;
        }

HTML

<body>
    <section>
        <article class="them">
            <p>Lorem ipsum, dolor sit amet.</p>
        </article>
        <article class="me">
            <p>Lorem ipsum.</p>
        </article>
        <article class="me">
            <p>
                Lorem ipsum dolor sit, amet consectetur adipisicing elit.
                Nostrum tempore excepturi dolore nam? Odio architecto
                tempora maiores corrupti nihil autem necessitatibus natus
                consequuntur adipisci hic nisi quaerat voluptate, incidunt
                beatae?
            </p>
        </article>
        <article class="them">
            <p>
                Lorem ipsum dolor sit amet consectetur adipisicing elit.
                Repellat officia delectus sequi quo quas!
            </p>
        </article>
    </section>
</body>

This code ensures text bubbles shrink horizontally depending on the content, wrapping only as necessary without surpassing 75% maximum width.

If you encounter any issues, please feel free to reach out. Thank you!

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

Arrangement of Columns in Bootstrap 4 - Three Columns Aligned Vertically on the Left, One on the Right

My goal is to achieve a Bootstrap 4 layout like the one shown in the image linked below: https://i.sstatic.net/gY6m5.png For large devices, I want the Search Form, CTAs, and Button ads to be arranged vertically in a column that spans 4 units, while the C ...

The HTML component fails to acknowledge width settings

I seem to be having trouble identifying an issue or perhaps I am misunderstanding something (I am using daisyui + nx + tailwind css + angular). To simplify my problem, let's consider the following scenarios: In the first scenario, I have: <div cl ...

Center the image to always align with the text

I am looking to display an image alongside some text, where the number of text lines can vary. It could be one, two, or three lines of text. Here's how it should be handled: If there is only one line of text: The image should be centered with the te ...

Angular 9 introduces a fresh approach to compiling alternate components

I am trying to append HTML to a div and have it compile the variables, loops, and all the Angular component elements within the string. The HTML content is being uploaded via a text file. While I am aware that this can be achieved using $compile in Angular ...

Arranging content within columns according to their column position

As I design a grid with three columns, each grid box contains a div with a maximum width of 280px. Sometimes the grid columns exceed this width. To achieve my desired layout, I aim to align the content in the grid boxes so that the left column aligns to th ...

Is it possible to automatically mute an HTML 5 video when closing the modal?

Is there a way to pause a video that plays in a modal and continues playing in the background when the modal is closed? I am using the Materialize library. <script src="https://code.jquery.com/jquery-2.1.1.min.js"></script> <!-- Compiled ...

I am unable to access the Xml data using VBA's `selectsinglenode` function as it is returning nothing

Below is the XML data: <NewZipCdListResponse> <cmmMsgHeader> <requestMsgId/> <responseMsgId/> <responseTime>20220526:085103847</responseTime> <successYN>Y</successYN> <returnCode>0 ...

Recaptcha is functioning properly on smartphones, however, it is experiencing difficulty on computers

Hey there! I encountered an issue with my website where the recaptcha isn't working on the desktop version. It's strange because I've used the same code successfully on other sites before. I attempted to fix it by creating a new recaptcha a ...

CSS - Creating a stylish break line for link boxes

Struggling with creating a box that includes linked text and a line break. However, the issue arises when the line breaks, causing the box to also break. After trying multiple options, I still can't seem to find a solution. Check out my attempt her ...

A page that appears blank is produced when using 'style="display:none"'

I am encountering an issue where using style="display:none" on an audio element in my code is causing the entire page to disappear instead of just hiding the audio element. I also tried using style="visibility:hidden" but had the same outcome. There are ...

Creating engaging animations with styled components in ReactJs

I have embarked on the journey of crafting a testimonial section that bears resemblance to the testimonials displayed on the website www.runway.com. Leveraging styled-components, I've made progress in piling up the cards at the center of the screen, w ...

What is the best way to unselect the "all" selector if one of the inputs is no longer selected?

I am facing an issue with a search filter functionality. When all filters are selected and then deselected individually or together, the "all" button remains selected. I need help in ensuring that when any filter is deselected, the "all" button also gets d ...

What is the reason behind fullPage.js only displaying the first page while hiding all others?

My website development is currently hindered by an issue with fullPage js. Only the first page is visible when using fullPage js, even though the links are properly set up on the dev site. As a result, I have to disable fullpage in order to make any progre ...

hover-over images

Hello there! I'm currently experimenting with simple rollover images for a website that I am working on. However, I've noticed that when I try the effect in Firefox, it seems to move other elements on the webpage. Do you have any suggestions on h ...

Transform pixel padding into percentage ratios

I've been searching through various discussions to find a solution, but none of them seem to fit my particular scenario. My issue involves a hyperlink with absolute positioning inside a div with relative positioning. The padding and margins are curre ...

What is the best way to maintain filter selections on the subsequent page using PHP Laravel?

There seems to be an issue with filtering my user table on the page. While I can successfully filter the first page of users, when I navigate to the second page, everything reverts back to default instead of remembering the form inputs. Here is a snippet o ...

When a JavaScript click event is triggered, IE8 can reset certain margins to zero

I am experiencing an issue with 3 divs containing content that becomes visible when clicking on 3 buttons. You can see a demonstration of the problem here: At times, when I click one of the buttons, the layout seems to be disrupted as shown here: It appe ...

Refresh the page on the same tab after making an AJAX request

HTML: <table border="1"> <tr id="main_account"> <td width="50%"> <h3 style="margin-left:10px">Details</h3> <table width="270"> <tr> <td& ...

Discover the secret sauce to effortlessly adding text upon hovering over a button

I am completely new to CSS and only know the basics. Recently, I stumbled upon this code online that creates a button. However, I want to use an image inside the button, add a color overlay when hovered, and display text saying "LEARN MORE" upon hovering ...

Creating a Client-side Web Application with Node.js

As I search for a versatile solution to bundle an HTML5 web application (without server dependencies) into a single executable app using node.js and the Linux terminal on Ubuntu, I have experimented with tools like wkpdftohtml and phantomjs. However, these ...