Nix
Nix

Reputation: 5998

Applying a max-width larger than 100%

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

Upvotes: 3

Views: 2788

Answers (3)

Scott Selby
Scott Selby

Reputation: 9570

http://jsfiddle.net/gdRaB/10/

I put the div in a container div

<div class="container">
<div class="list">
    <ul>
        <li>Banana</li>
        <li>Molten Boron</li>
        <li>Steak sauce</li>
        <li>Unicorn tears</li>
        <li>Ground-up griffins</li>
        <li>Semi-alive hobgoblins (frozen)</li>
    </ul>
    </div>
</div>



.container{
    width: 500px;
    overflow: auto;}

.list{
    width: 5000px;
}

ul {
    width: 5000px;
    overflow: visible;
    width: auto;
    display: inline-block;
}

li {
    background: #ccc;
    display: inline-block;
    margin: 0 5px;
    padding:2px 5px;
}​

Upvotes: 0

canon
canon

Reputation: 41665

Unless I misunderstood your question, you can simply add white-space: nowrap; to your ul (fiddle). Then you'll get the desired horizontal scrollbar upon overflow.

[Edit]: and text-align: center; to your div (fiddle)

Upvotes: 3

Adam Jenkins
Adam Jenkins

Reputation: 55613

I think what you want is min-width, not max-width

ul {
   **min-width: 5000px;** /* Doesn't override */
   width: auto; /* Calculated to 500px or less */
}

http://jsfiddle.net/gdRaB/5/

Upvotes: 1

Related Questions