div horizontal scroll is not working automatic
I am trying to develop a div horizontal scroll based on content width. But that is not working perfect please help me. This works if i set ul width to specific px but not auto
This is my CSS and HTML
.sri{
width:550px;
height:40px;
margin:auto;
padding:0px;
overflow-x:scroll;
overflow-y:hidden;
}
.sri ul{
margin:0px;
padding:0px;
list-style:none;
width:auto;
}
.sri ul li{
width:auto;
margin:0px 5px;
padding:0px 5px;
float:left;
height:auto;
background:#CCCCCC;
color:#333333;
}
<div class="sri">
<ul>
<li>something content comes here</li>
<li>something content comes here</li>
<li&开发者_如何学Pythongt;something content comes here</li>
<li>something content comes here</li>
<li>something content comes here</li>
<li>something content comes here</li>
<li>something content comes here</li>
<li>something content comes here</li>
<li>something content comes here</li>
<li>something content comes here</li>
<li>something content comes here</li>
<li>something content comes here</li>
<li>something content comes here</li>
<li>something content comes here</li>
</ul>
What you're seeing when the width of the UL is set to auto is the natural behaviour of floated elements.
2 options:
1) You could use a table instead of an unordered list. This will lay out horizontally no matter what the container width is.
2) You could set the width of the UL dynamically based on the number of elements you have (width of li * number of li's = total width of UL). I'm guessing, as there are a variable number of items that can appear in this list that you're generating the list server-side? If that's the case, you should be able to set the UL width quite easily.
As far as having no scrolling when there's not enough items - just set overflow-x:auto;
Easiest fix in this case is to set a massive width like width: 9999px
on .sri ul
:
Live Demo
Oops: that works in IE8 and Chrome, but not Firefox/Opera. Investigating.
Here's attempt #2:
display: table
and friends was the only way I could find to get this to work consistently.
There won't be a scrollbar if the content isn't wider than 550px
.
Live Demo
HTML:
<div class="sri">
<ul>
<li>something content comes here</li>
..
</ul>
</div>
CSS:
.sri {
width: 550px;
height: 40px;
margin: auto;
padding: 0;
overflow-x: auto;
overflow-y: hidden
}
.sri ul {
margin: 0;
padding: 0;
list-style: none;
display: table
}
.sri ul li {
margin: 0 5px;
padding: 0 5px;
background: #ccc;
color: #333;
display: table-cell;
white-space: nowrap
}
精彩评论