Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fit width of div tightly to multi-line span

Tags:

html

css

I want to have a div with a given max-width that tightly fits its width to its child's span. Everything works fine as long as the span is only one line, but as soon as the line break happens the parent div will have the maximum width.

.content {
  margin: 10px;
  max-width: 150px;
  border: 1px dotted black;
  display: inline-block;
}
<div class="content">
  <span>1 line works</span>
</div>
<br>
<div class="content">
  <span>2 lines dont workworkwork</span>
</div>

The first div has a tight fit, the second div however is set at the maximum width - but it could be tighter and I want it tighter. See also my pen at http://codepen.io/sheinzle/pen/gpVjbG

Is getting a tighter fit even possible in HTML?

like image 355
Simon Heinzle Avatar asked Aug 25 '15 15:08

Simon Heinzle


2 Answers

Thanks for all the answers so far. I still really hope that somebody has a pure HTML/CSS solution.

In the meantime, here is a quick fix with the help of JavaScript (CSS/HTML unchanged from OP). It probably doesn't catch all the edge cases, but it works for now. Pen is at http://codepen.io/sheinzle/pen/MwNdgO

document.addEventListener("DOMContentLoaded", function(event) {
  // get list of all spans
  list = document.querySelectorAll('.content span');
  for (var i=0; i<list.length; i++) {
    // retrieve width of span and apply it to parent
    w = list[i].offsetWidth;
    list[i].parentNode.style.width = w+"px";
  }
});
.content {
  margin:10px;
  max-width: 150px;
  border:1px dotted black;
  display:inline-block;
}
<div class="content">
  <span>1 line works</span>
</div>
<br>
<div class="content">
  <span>2 lines do workworkwork</span>
</div>
like image 136
Simon Heinzle Avatar answered Oct 11 '22 12:10

Simon Heinzle


Use flexbox and place your styling on the inner span:

.content {
  margin:10px;
  max-width: 150px;
  display: flex;
}
.content span{
  flex: 0 1;
  border:1px dotted black;
}
<div class="content">
  <span>1 line works</span>
</div>

<br>

<div class="content">
  <span>2 lines alsoworkhere</span>
</div>
like image 2
Flyke Avatar answered Oct 11 '22 13:10

Flyke