Search code examples
htmlcsswidthhorizontal-scrolling

CSS: Fitting width to content or wrapper - whichever is wider


So I have a set of list items, and I'm trying to get mouse-over highlighting to look correct on them. Here's the html:

<div id="wrapper">
  <div id="box">
    <div class="item">Lorem ipsum dolor sit amet, sit nonumy utamur ponderum ex</div>
    <div class="item">Eu liber libris sit, qui aeque primis an</div>
  </div>
</div>

Then, I'm giving the wrapper overflow: auto. Thus if the list items are too long, the wrapper will allow horizontal scroll:

#wrapper {
  overflow: auto;
}

And here's a JSFiddle that I'm working with:
https://jsfiddle.net/codesmith32/e9se5120/


Now, my goal is this:

  1. When the items in the list are all shorter in width than the wrapper (thus, no horizontal scrolling), the highlight should stretch all the way from left-to-right:

Case 1. Working

  1. But, when the items are long enough to make the wrapper scroll, the highlight should stretch the length of the longest item, i.e., the full scroll width of the wrapper.

Case 2. Working


By default, case 1. works fine, and the highlight stretches across when the items don't cause horizontal scrolling. But when they are too long, the highlight only stretches to the width of the box, but not the width of the items, thus failing case 2.:

Case 2. Fails by default

I seem to have found that setting display: flex on the wrapper will cause the width of the items to fit the text and highlight correctly when they cause horizontal scrolling. However, then it doesn't stretch the full width of the box when the items don't generate horizontal scrolling, failing case 1.:

Case 1. Fails with display: flex

I also thought that giving the #box element min-width: 100% would force it to be at least that width. But instead, it then works for case 1. and not for case 2. again, despite the wrapper's display: flex.

Any ideas?


Solution

  • Use flex-grow:1 on the child of the wrapper. https://jsfiddle.net/3p9kyu7v/1/

    #wrapper {
      width: 100%;
      height: 300px;
      overflow: auto;
      border: 1px solid #808080;
      /* remove * to toggle -> */
      display: flex;
      /**/
    }
    #box {
      flex-grow: 1;
      padding: 10px;
    }