How can I include the width of "overflow: auto;" scrollbars in a dynamically sized absolute div?

Tristan picture Tristan · Dec 7, 2011 · Viewed 16k times · Source

(First question on Stack Overflow. Hope I'm doing it right.)

I'm trying to create a floating menu that inherits its width from its content (since I don't know the width in advance, i.e. loaded from a URL). I can do this by having the menu div absolutely positioned without setting a width or height.

The problem occurs when the content is tall enough to require scrolling. I set "overflow: auto;" so that it can be scrolled vertically, but the new scrollbar doesn't make the div wider. Instead, the div stays the same width, and the scrollbar juts into its previously nicely sized content, forcing the content to wrap.

Example: http://jsfiddle.net/w7Mm8/

In the example: in Firefox, "five" gets wrapped onto the next line, but in Chrome (for Mac at least), its all shown on one line.

Any elegant way to do this without explicitly setting the width of the menu to include the width of the scrollbar?

THANKS!

Answer

bookcasey picture bookcasey · Dec 7, 2011

You have a few options.

Use white-space:nowrap; and some padding.

Use overflow: scroll;, which adds an extra scrollbar on the bottom, but fixes the wrapping problem in Firefox.

Use overflow-y:scroll which is CSS3 and is supported by only modern browsers.