So, I have a list of inline-block list items. They all vary in width, but are always on the same line. The number of list items may also vary, so I can not predict the width of the list as a whole. The list should always be centered in its parent container, but when the width exceeds 100%, it should gain a horizontal scroll rather than extending over two lines.
Now, as far as I understand, if I set the width to auto, it is actually set to shrink-to-fit – essentially meaning max-width: 100%;, which is not what I want.
Is there a way for me to achieve this reliably with CSS alone?
Markup
<div>
<ul>
<li>Banana</li>
<li>Krypton</li>
<li>Molten boron</li>
</ul>
</div>
CSS
div {
overflow-x: auto;
width: 500px;
}
ul {
max-width: 5000px; /* Doesn't override */
width: auto; /* Calculated to 500px or less */
}
li { display: inline-block; }
It should be noted that this is a responsive layout, so the width of the container is not exactly fixed, but I’m not afraid of manual labour.
My JS Fiddle: http://jsfiddle.net/TheNix/gdRaB/
My question is similar to CSS dynamic width larger than 100% except my child elements are not floated, ergo still in the flow (I have control over this).
Regarding width: auto; in the spec: http://www.w3.org/TR/CSS2/visudet.html#inline-replaced-width
Unless I misunderstood your question, you can simply add
white-space: nowrap;to yourul(fiddle). Then you’ll get the desired horizontal scrollbar upon overflow.[Edit]: and
text-align: center;to yourdiv(fiddle)