Tips for adjusting the width of a div to accommodate word wrapping

Can a div element be resized when word wrap occurs? To illustrate, take a look at this example from a similar query:

.mypost {
  border: 1px solid Peru;
  margin: auto;
  min-width: 200px;
  display: inline-block;
  background: red;
}

.test {
  margin: 10px;
  background: cyan;
}
<div class="mypost">
  <div class="test">I represent the imagdfv fdvdsdfsdfve.</div>
</div>

If you resize the window to cause word wrapping, an empty blue space will appear to the right of the text. I would like the blue area to shrink until it reaches the end of the first line.

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

(The image demonstrates forcing word wrap and I want the blue area to decrease.)

Is this achievable?

Answer №1

In summary: The answer is no.

When word wrapping occurs, the block-level element containing the text will expand to fill its container regardless of where the text breaks.

While it's possible to use javascript to find a minimum-width box of the starting height, this method can be inefficient due to repeated redraws and is not as CSS-friendly:

target = document.getElementsByClassName('test')[0];
height = target.clientHeight;
minWidth = 1;
maxWidth = target.clientWidth;
while(maxWidth - minWidth > 1) {
  var newWidth = (minWidth + maxWidth) / 2;
  target.style.width = newWidth + "px";
  if(target.clientHeight > height) {
    minWidth = newWidth;
  }
  else {
    maxWidth = newWidth;
  }
}
target.style.width = maxWidth + "px";
.mypost {
    border: 1px solid Peru;
    margin: auto;
    width: 300px;
    display: inline-block;
    background: red;
}
.test {
    margin: 10px;
    background: cyan;
}
<div class="mypost">
    <div class="test">I represent the imagdfv fdvdsdfsdfve.</div>
</div>

Answer №2

Typically, div elements are considered to be block-level elements, which means they automatically occupy 100% of the width of their parent element. One way to adjust the width of a div based on its content is by using JavaScript.

However, if your main concern is confining the background color within inline content (such as text and images), you can simply change the display property to "inline" with the display: inline declaration. In this case, you will need to eliminate any margins and include padding in the parent element instead.

I have provided an example below where I have made modifications to your code. I added display: inline to the .test class, removed margin: 10 from

.test</gode>, and inserted <code>padding: 10
to .mypost. I also adjusted the line-height and font-size to ensure there are no gaps between lines.

The snippet below allows for an interactive demonstration where you can edit the content of the div to observe how word wrapping functions:

You may find a similar question regarding removing extra spaces caused by word wrap in a fitted element here without satisfactory answers: How to remove extra space caused by word wrap in shrunk to fit element?

Answer №3

My personal preference would be to set the inner div to have a display: inline-block; style.

Therefore:

    .mypost {
        border: 1px solid Peru;
        margin: auto;
        min-width: 200px;
        display: inline-block;
        background: red;
    }
    .test {
        display: inline-block;
        margin: 10px;
        background: cyan;
    }
    <div class="mypost">
        <div class="test">I represent the imagdfv<br/>fdvdsdfsdfve.</div>
    </div>

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

Switching between dynamic Angular template classes

Creating an Angular HTML template with reactive form: <div class= "one"> <button class = "verticalButtonClass" (click) = "onClick()"> Label4 </button> </div> <div class = "two"> </bu ...

Transferring information to the repository

Encountering an issue with sending the entered data to the database using the php and html form post method. Upon clicking submit, only the header is successfully sent to the database, while everything else triggers errors. Note: Undefined Index: Image Not ...

The jQuery "Chosen" select accordion is experiencing the issue of its height becoming too large and then snapping back into place

I have integrated jQuery Chosen with a Twitter Bootstrap Accordion. The issue of the Chosen dropdown being clipped by the accordion body has been resolved by referring to solutions provided in this thread. However, I am still encountering another problem w ...

Trouble displaying AngularJS $scope.data in the HTML code

I'm experiencing an issue where the data received from a POST request is being logged in the console, but is not displaying on the HTML page. Despite having a controller set up, the {{user}} variable is not appearing on the HTML page. While I can se ...

Switch up the background image when hovering over it

Could the proportions of the image be contributing to the issue at hand? #menu { background: black; width: 100%; height: 45px; } #menu ul { text-decoration: none; list-style-type: none; } #menu li { text-decoration: none; display: inline; font-size: ...

Error encountered while validating jQuery word cloud

Can anyone please assist me with validating a jQuery word cloud in HTML5? I'm encountering issues with all of the rel values showing this error message: "Bad value 1 for attribute rel on element a: Not an absolute IRI. The string 1 is not a registere ...

Error: Material-UI prop type validation failed - Please specify either `children`, `image`, `src`, or `component` prop

Despite having an image prop in CardMedia, I kept encountering this error. Here is a snippet of the code: Error description: const Post = ({ post, setter }) => { const classes = useStyles(); return( <Card className={classes.card} ...

What is the way to modify the standard request for an "@" in the email address?

Although I've successfully changed the error message for when the user forgets to type in their email, I'm now wondering how to modify it when the user enters their email in the wrong format. Below is the code I've written in the style of B ...

How to retrieve data from a form object sent via cloud function using App Script

Currently, I am in the process of developing a web application that can extract files from a web form and store them in a designated Google Drive folder. After the user submits the form, my goal is to trigger a cloud function using google.script.run while ...

HTML formats for tables in Google Chrome

Having trouble pinpointing the error in this code. It works perfectly in Firefox and IE, but in Chrome, the inner cells are not centered as intended. <table cellpadding="0" cellspacing="0" style="width: 100%"> <tr> <td rowspan=" ...

Having difficulty accessing the live server on VS Code for download

I'm having trouble installing the live server extension in my VS Code. When I search for "live server" in the extensions marketplace, I can't seem to find it among the results. Can someone please suggest an alternative method for installation? ...

What is the best way to create a box in the shape of an octagon

Trying to achieve the unique box design shown below using CSS. I researched various resources, such as https://css-tricks.com/examples/ShapesOfCSS/, but encountered an issue with the purple border cutting edges. Attempted using an octagon shape without su ...

Hovering over the Bootstrap menu to activate clickable options

I have made modifications to the bootstrap navigation using jQuery so that instead of clicking, you can simply hover to enable the dropdown menu. However, I am facing an issue where the first menu option is not clickable. For example, currently the "BLOG" ...

What is the method for altering the background color of an input field upon entering text?

As a beginner in Javascript and jQuery, I am struggling to understand why my code is behaving the way it does. I have written two similar functions aimed at changing the background color of an input field. The objective is to set the background color of t ...

The HTML email appears distorted on Yahoo and Outlook, but displays correctly on all other platforms

Basically, I have an HTML email that was converted from a PSD file. I sliced the layers, made some changes to the URLs, and did a test email. The email looks fine on most email clients, but when I send it to Yahoo Mail or Hotmail/Outlook and open it in Chr ...

How to Incorporate Multiple React Components in an HTML File

Attempting to integrate React code into an HTML file has been a challenging process for me. I've been following the official React documentation and successfully implemented their basic like button starter code on my page. Initially, everything worked ...

Is there a way to dynamically alter the names of CSS files using jQuery? Just as an example, transforming "file2.css" into "file1.css"

var device = (/iphone|ipad|ipod|android|blackberry|mini|windows\sce|palm/i.test(navigator.userAgent.toLowerCase())) if(device){ <link href="mobil.css" rel="stylesheet" type="text/css" media="screen"> } else { ...

Using various HTML elements within Phonegap applications

Is it possible to include multiple HTML files in a Phonegap application? ...

Issue with flex-grow property not functioning as expected in Internet Explorer 11

Hello! I'm running into an issue with flexbox in Internet Explorer: http://jsfiddle.net/EvvBH/ I've noticed that the #two element has flex: auto, which is meant to make it expand to fill the container, even if there's limited content. Ho ...

Using Node.js and Express, the CSS does not load due to route parameters

I'm currently working on a basic website project using Node.js, Express, and the EJS template engine. I've run into an issue where my external CSS files are not loading properly on routes that contain route parameters. Here's a snippet of my ...