Question: display: inline-block does not make width as small as possible with wrapped contents

Question

display: inline-block does not make width as small as possible with wrapped contents

Answers 4
Added at 2016-12-30 02:12
Tags
Question

I have a div that has inline-block and a max-width set on it, as well as some text content that may wrap inside. My problem is that the div always takes the maximum width possible, but only if the text wraps. I wish to make the div take the smallest width possible, in response to text wrapping.

div {
 
  max-width: 120px;
  width: auto;
  display: inline-block;

  border: 1px solid black;    
  padding: 0.2rem;
  
}
<div>Reallylongword test</div>

Actual Result:
Actual Result

Desired Result:
Desired Result


This does not work with restricting the width with a parent, either.

I have searched around, and my code is using this method. I have also tried this (Fiddle), but it just doesn't work. I am of aware using word-break: break-all, but that is just really ugly.

Thank you.


Update

I am trying to make a navbar. It is currently using flexbox, not display: inline-block. I just (or at least I thought I did) isolated the problem to single nav element. Apparantly, not all the answers seemed to match my original navbar problem. I'm sorry. I will preserve the original post if I don't get an answer to my actual problem.

Answers to

display: inline-block does not make width as small as possible with wrapped contents

nr: #1 dodano: 2016-12-30 02:12

This is simply how browsers size an element when text wraps. The same thing happens with table cells. If you are using very specific, static content you could put a hard break </br> where you want the text to wrap. This solves the issue but leaves your content very inflexible. However considering you are being very specific in your container size this might work for you.

Would it be possible to see your content and the design you are trying to achieve? It would help with offering solutions.

nr: #2 dodano: 2016-12-30 02:12

Have you tried to use the span tag. It's an inline element and inline elements are only as wide as what's inside it. Once you've used span you can change display: inline-block to just display: inline;

I hope this helps

div {
 
  max-width: 120px;
  width: auto;
  display: inline;

  border: 1px solid black;    
  padding: 0.2rem;
  
}
<div><span>Reallylongword test</span></div>

nr: #3 dodano: 2016-12-30 02:12

From this answer in one of your linked questions: display: table-caption instead of inline-block does what you want.

div {
  max-width: 120px;
  width: auto;
  display: table-caption;

  border: 1px solid black;    
  padding: 0.2rem;
}
<div>Reallylongword test</div>

nr: #4 dodano: 2016-12-30 08:12

Can you adjust your max-width value like below?

div {
 
  max-width: 110px;
  width: auto;
  display: inline-block;

  border: 1px solid black;    
  padding: 0.2rem;
  
  
}
<div>Reallylongword test</div>

Source Show
◀ Wstecz