Hello! Tell me please! There are 3 albums-menu ul and on each (as the cover) always a different number of images from 1 to 4

If one image is in a block then width:100% i.e. totally 400x400
If two then 50% - it is necessary that the pictures automatically go under 400x400
If three then 30% - in general, the block size is fixed and the pictures themselves should fit and not leave empty places.

How to compose js which will count the count of li in the class and depending on the count will work the desired css width:% and the images will completely fill the ul block

 <style> ul{ width:400px; height:400px; } </style> <body> <ul class="block"> <li class="img"></li> </ul> <ul class="block"> <li class="img"></li> <li class="img"></li> </ul> <ul class="block"> <li class="img"></li> <li class="img"></li> <li class="img"></li> </ul> </body> 

    2 answers 2

    http://jsfiddle.net/mj43rxLj/1/

     var i,j,amount,items,lists = document.getElementsByTagName('ul');//Ищем все списки for(i=0;i<lists.length; i++){ items = lists[i].getElementsByTagName('li');//Ищем все li внутри ul amount = items.length; lists[i].className += ' amountBasedClass'+amount;//Присваиваем UL нужный класс } 

    Classes themselves think up. I gave an example of how I understood your task.

    • Keep in mind, you have to independently check for the presence of this class in the element, or make sure that the code is executed only once. - knes

    You can do without javascript:

     /* один элемент */ li:first-child:nth-last-child(1) { width: 100%; } /* два элемента */ li:first-child:nth-last-child(2), li:first-child:nth-last-child(2) ~ li { width: 50%; } /* три элемента */ li:first-child:nth-last-child(3), li:first-child:nth-last-child(3) ~ li { width: 33.3333%; } /* четыре элемента */ li:first-child:nth-last-child(4), li:first-child:nth-last-child(4) ~ li { width: 25%; } 

    Article original: Styling elements based on sibling count