24

I have a list like this:

<div>
   <ul>
     <li>one</li>
     <li>two</li>
     <li>three</li>
     <li>four</li>
   </ul>
 </div>

and the following CSS:

ul { 
     width: 160px;
     height: 100px;
     overflow: auto; 
     }
li { 
     width: 80px;
     display: inline-block;
     float: left 
     }

I'm trying to force the list items to display from left to right, that is

 one - two - three - four

My problem:
Doing it like this gives me two rows with two items each.

Question:
Is there a CSS way to force the list items to all be in a single row so I can use horizontal scrolling? Right now if I set overflow:auto I'm only getting vertical scrollbars, which I don't want.

I don't want to set this on the wrapping div. I'm just curious if there is a CSS solution I can use within the list alone.

Thanks for help!

animuson
  • 53,861
  • 28
  • 137
  • 147
frequent
  • 27,643
  • 59
  • 181
  • 333

5 Answers5

56

You can't really scroll floated content. Once it's floated, it's not calculated in the width or height of the parent container by default. Really the <ul> is just expanding to its set width and then not doing anything else.

Removing the float: left will make them scrollable. The only problem you'll have then is that there is the extra "space" between each inline-block. You can remove that by removing the line-breaks between each list item. It's not the prettiest thing. Normally I'd use a font-size: 0 and then reset the font-size in the list item.

You also need to make sure the items don't wrap to a new line when they hit the width of the element.

jsFiddle Examples:

animuson
  • 53,861
  • 28
  • 137
  • 147
39

Here's a working fiddle: http://jsfiddle.net/qnYb5/

Relevant CSS:

ul{
    list-style-type:none;
    white-space:nowrap;
    overflow-x:auto;
}

li{
    display:inline;
}
MetalFrog
  • 9,943
  • 1
  • 22
  • 24
  • 5
    The `height` there is not actually doing anything related to the scrollbar. In fact, it's just making the content cut off. http://jsfiddle.net/nPmLe/1/ - This answer is just misinformation hidden behind other properties which are actually doing the work. The height does not need constrained whatsoever. – animuson Mar 14 '12 at 21:20
2

You haven't constrained the height of the <ul>, so the browser is free to wrap the 'extra' elements onto their own line. You'll need a height: 1em or whatever to make sure the <ul> can't get taller, forcing everything to scroll horizontally.

Marc B
  • 356,200
  • 43
  • 426
  • 500
  • nope. Doesn't work. The list items don't seem to care and if I'm setting overflow: auto, I only get vertical scrolling. – frequent Mar 14 '12 at 18:35
2

Use overflow-x: scroll; on the div.

Fiddle with it here.

Krazer
  • 471
  • 7
  • 20
1

You can make it with css+javascript, e.g. (http://www.smoothdivscroll.com/v1-2.htm). Don't think there is a CSS-only sulution (that will work cross-browser).

daker
  • 3,430
  • 3
  • 41
  • 55