skip to Main Content

The code snippet pretty much explains the issue. If I want to make a div only take as much space as its text, how can I do it if the text has wrapped into a new line???

enter image description here

.outer-container {
  width: 600px;
  height: 300px;
  background: pink;
}

.text-container-bad, .text-container-good {
  display: inline-block;
  margin-bottom: 30px;
  background: cyan;
}
<div class="outer-container">
  <div class="text-container-good">
    Shorter text that doesn't wrap and the container only takes as much space as the text
  </div>
  <div class="text-container-bad">
    This is a longer text that wraps and the container takes more horizontal space thaaaaaaaaaaaan its text
  </div>
</div>

2

Answers


  1. This problem doesn’t have a straightforward CSS-only solution for all cases.

    It’s a little tricky due to the way CSS works with wrapping and block dimensions. Here’s a workaround to get closer to the desired effect using CSS…

    We can use float: left which makes the container only as wide as its content, even if the content wraps to multiple lines.

    .outer-container {
      width: 600px;
      height: 300px;
      background: pink;
      overflow: auto;
    }
    
    .text-container-bad,
    .text-container-good {
      float: left;
      margin-bottom: 30px;
      background: cyan;
      margin-right: 20px;
    }
    <div class="outer-container">
      <div class="text-container-good">
        Shorter text that doesn't wrap and only takes as much space as the text
      </div>
      <div class="text-container-bad">
        This is a longer text that wraps and takes more horizontal space thaaaaaaaaaaaan its text
      </div>
    </div>
    Login or Signup to reply.
  2. There’s not an easy solution to this with CSS because of how CSS calculates the width of the divs. It doesn’t recalculate the width after rendering the line breaks.

    If you you want to accomplish what the title of this post suggests, which is to make the wrapped text as wide as its container div, you can add word breaks:

    .text-container-bad, .text-container-good {
      display: inline-block;
      margin-bottom: 30px;
      background: cyan;
      word-break: break-all; /* Add this */
    }
    

    This will make it so ‘tha…an’ extends all the way to the end of the first line before breaking onto the second line.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search