CSS auto change ul width when li increase (floating left)
Asked Answered
S

1

9

I have a problem to auto fix UL`s width that LI can float straightly.

If I change css, set UL with a width like '1000px', not 'auto'; that what I want can be done.

However, is there other any settings only by CSS also can achieve same result?, because I want to auto change UL`s width as increasing number of LI.

    Now is like
    div ul-------------------------------div ul
            |   ///////      ////////       |
            |   /////// li   ///////  li    | 
            ---------------------------------
               ///////     ////////
               ////// li   ///////  li

   I want to be like this  
        div                                 div
          ul-------------------------------------------------------------ul
            |   ///////      ////////       |  ///////      ////////    |
            |   /////// li   ///////  li    | /////// li   ///////  li  |
            -------------------------------------------------------------

http://jsfiddle.net/KgyHZ/21/

HTML

<div class='test'>
    <ul>
        <li></li>
        <li></li> 
        <li></li>
        <li></li>
    </ul>
</div>

CSS

.test{
    width: 500px;
    height: 100px;
    overflow: hidden;
}
.test > ul{
    list-style:none;
    width: auto;
    height: 100%;
    background-color:#999;
    display: block;
    padding: 0px;
    margin: 0px;
}
.test > ul > li{
    float: left;
    display: block;
    height: 100%;
    width: 180px;   
    background-color:#99c;
    margin-right:10px;
}

Thank you very much for your advice.

Slapstick answered 13/6, 2013 at 20:5 Comment(2)
I'm not sure I understand what you're saying. Could you provide an illustration of how you want it to look like?Introspect
you can do percentage width for the li instead of pixels, like .test > ul > li { width: 25%; } /*reduce this if there is margin left/right*/Beforetime
D
30

You could achieve this, by setting your 'li' to display as inline-block in stead of floating them. You should then set the white-spaceon the ul to nowrap to force them all on the same line. Something like this:

ul{
    list-style:none;
    white-space: nowrap;
}
ul > li{
    display: inline-block;
}

You can now add as many li's as you want, and your ul will keep growing.

There are a few things that you should take into account when using this technique:

  • This might produce a horizontal scrollbar, and users hate those
  • You may need to add some extra css to make the inline-block work in legacy browsers
  • Your ul width will not exceed the width of its parent as demonstrated in the fiddle example below. The li's are in fact overflowing their parent. Not realy a problem, but you may have to be creative when working with backgrounds on the ul.

For a simple fiddle that demonstrates the technique: http://jsfiddle.net/KgyHZ/213/

Disc answered 13/6, 2013 at 20:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.