horizontal scrollbar for ul

2019-02-04 13:40发布

For some reason, I can't prevent the UL and it's LI's from wrapping. I want the UL's width to be exactly the width of the LI's on one line (without wrapping) and if the UL becomes wider than the nav-div (800px), I want a scrollbar within the nav so I can scroll the LI.

I tried pretty much anything with display, whitespace, width's and height, but I can only get it to work if I give the UL a certain width. This, however, is not an options, since the page is generated and can contain 1-20 LI's.

Does anyone know how to make a scrollbar come up without setting the UL's width?

HTML:

<div id="nav">
     <ul id="navbuttons">
          <li>Some text</li>
          <li>Some text</li>
          ...
     </ul>
</div>

CSS:

div#nav
{
    height: 100px;
    width: 800px;
    margin-left: auto;
    margin-right: auto;
}

div#nav ul li
{
    margin-right: 15px;
    float: left;
    font-size: 12px;
    list-style-type: none;
}

5条回答
疯言疯语
2楼-- · 2019-02-04 13:58

You can use display: inline-block; white-space: nowrap; for the wrapper and display: inline or display: inline-block for the children.

So, it would look like this: http://jsfiddle.net/kizu/98cFj/

And, if you'll need to support IE add this hack in conditional comments to enable inline-blocks in it:

.navbuttons,
.navbuttons LI {
    display: inline;
    zoom: 1;
}
查看更多
不美不萌又怎样
3楼-- · 2019-02-04 14:01

By setting the width on the <ul> to inherit you can use the overflow property to set the overflow behavior of the element. With the value scroll, all of the element's contents will scroll (in both x and y directions) if the height and the width of the contents overflow that of the box:

div#nav ul
{
    overflow: scroll;
    width: inherit;
    height: inherit;
}
查看更多
▲ chillily
4楼-- · 2019-02-04 14:04

Caveat: Untested

Would you not just want to set a width for the li item

div#nav ul li {    
   margin-right: 15px;     
   float: left;     
   font-size: 12px;     
   list-style-type: none;
   width: 100px;
}

And then set the width to a fixed width and overflow on the UL to scroll?

div#nav ul {
    width: 800px;
    overflow: scroll;
}   

This would cause you UL to scroll when your li's went past say 8, is that what you're after?

查看更多
做个烂人
5楼-- · 2019-02-04 14:11

try this

ul {
   white-space:nowrap;
}

li {
   display:inline;
}
查看更多
迷人小祖宗
6楼-- · 2019-02-04 14:13

Add the following rule:

div#nav ul {
   overflow-x: hidden;
   overflow-y: scroll;
   white-space: nowrap;
}
查看更多
登录 后发表回答