Forcing nested block HTML elements to be the same width as content using CSS

Ensure a nested element within a fixed width container with a scroll-bar still retains the width of its content.


When creating websites, one will sometimes need content to fit in one line of an HTML element within a parent that is set to overflow:scroll. This can be quite problematic sometimes, especially if you want that element to be styled.


To fit text into a single line of an element we can use:


<div id="container"><div id="long_div">very long text very long text very long text very long text very long text very long text</div>  
</div>     
<style>  
 #container {     
  width : 400px;     
  height : 300px;     
  overflow-x : scroll;     
 }     
 #long_div {     
  white-space : pre;     
  background : yellow;     
  width : auto;     
 }  
</style>  

The above style will fit the text onto a single line (given there are no line breaks) but the div will not be sized correctly, this problem is usually fixed when we declare width:auto, but in this case the div sizes to the width of its parent.



This problem could be solved by changing the child div's display to inline-block, but if multiple child elements are wanted in a block style within the container, this will not be effective.


Solution

By floating the child div to the left, it will act like an inline-block element in that it will extend the element to the width of the content with width:auto.


This will allow you to add the desired styles to the div.


#long_div {     
 white-space : pre;     
 background : yellow;     
 width : auto;     
 float : left;     
}



Christopher Thornton@Instructobit 6 years ago
or