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?
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>
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With