CSS auto change ul width when increasing li (floating left)

I have a problem with automatically setting the UL width, which the LI can float directly.

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

However, are there other CSS-only settings also to achieve the same result ?, because I want to automatically change the UL width as the number of LIs increases.

  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; } 

Thanks so much for your advice.

+6
source share
1 answer

You could achieve this by setting β€œli” to display as inline-block instead of floating. Then you must set white-space to ul on nowrap to force them all on the same line. Something like that:

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

Now you can add as many faces as you want, and your ul will continue to grow.

There are several things you should consider when using this method:

  • This can lead to a horizontal scrollbar, and users hate these
  • You may need to add extra css to make inline-block work in legacy browsers
  • Your ul width will not exceed the width of its parent, as shown in the example script below. li actually overwhelm the parent. Not a problem, but you may need to be creative when working with ul backgrounds.

For a simple violin demonstrating the technique: http://jsfiddle.net/KgyHZ/213/

+23
source

Source: https://habr.com/ru/post/947244/


All Articles