skip to Main Content

By default, when text wraps, the width of the container becomes the max width. Instead, I want the width to fit the wrapped text.

div {
  border: 1px solid red;
  max-width: 100px;
  display: inline-block;
}
<div>
qwertyuiop 
</div>
<div>
qwertyuiop qwertyuiop 
</div>

In the example above, I want the 2 boxes to have the same width. Is this possible without JS?

2

Answers


  1. Yes, it is possible to achieve the desired behavior where the width of the container fits the wrapped text using CSS only. You can use min-content for the width property to achieve this. Here’s how you can do it:

    div {
        border: 1px solid red;
        max-width: 100px;
        display: inline-block;
        width: -moz-min-content; /* For Firefox */
        width: -webkit-min-content; /* For Chrome, Safari, and Opera */
        width: min-content; /* Standard syntax */
    }
    <div>
      qwertyuiop
    </div>
    <div>
      qwertyuiop qwertyuiop
    </div>
    Login or Signup to reply.
  2. Make the container fit the text with lineWrapping and ensure both boxes have the same width, you can use a combination of inline-block and some adjustments to the display propertie.

    https://developer.mozilla.org/en-US/docs/Web/CSS/white-space

    https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_text/Wrapping_breaking_text

    https://developer.mozilla.org/en-US/docs/Web/CSS/word-break

    div {
      border: 1px solid red;
      max-width: 100px;
      display: inline-block;
      white-space: pre-wrap; /* Ensure the text wraps while preserving spaces */
      word-wrap: break-word; /* Allow the text to break within words to prevent overflow */
      vertical-align: top; /* Align the divs to the top for consistent spacing */
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search