29

For various reasons, I have a nested ol inside of a div, where the contents of the list exceeds the size of the container.

Because the container has a fixed width, the list element's background does not exceed the viewable area of the container, yet the contents scroll properly.

I have created a jsFiddle showing a simplified example of what I'm trying to explain.

I would like the width of the contained element to match that of the overflowed content. In the jsFiddle, that would mean the red background doesn't get cut off midway.

Thanks.

div
{
    border: 1px solid black;
    margin: 33% auto;
    overflow: scroll;
    white-space: nowrap;
    width: 100px;
}

div > ol
{
   background: red;
   width: 100%;
}​
jeffjenx
  • 17,041
  • 6
  • 57
  • 99
  • why cant you just set the div's background to red? – kazinix Oct 04 '12 at 03:53
  • what is the point? Why do you want to do this? The "why" is important to figuring out a solution. And when you say you want the div to have the same width, do you mean you want the div to expand to the size of the list? – cegfault Oct 04 '12 at 04:26
  • 2
    The reason why is because I was using a list element for alternating rows with different backgrounds, so I couldn't just make the background of the div the same (variable `li` heights). Also, as stated, the container (the `div` in my **simplified** example) has a fixed width. – jeffjenx Oct 04 '12 at 13:51

1 Answers1

26

Just use display: inline-block. You can read more in the W3C specs.

Replace width:100% with display:inline-block in those two element styles.

ShouravBR
  • 685
  • 7
  • 10
  • 3
    I can't believe it was that easy, and that I didn't try that in all my experiments. Changing the display property does exactly what I want it to do. Thanks. – jeffjenx Oct 04 '12 at 13:48
  • Because, occasionally, my list element did not overflow the container, I had also ended up adding `min-width: 100%;` to the `ol`. – jeffjenx Oct 05 '12 at 02:30
  • 2
    Really? This is awesome but I'm not sure to understand why display block wouldn't use the overflow? – Yann Chabot Jul 18 '16 at 13:37