Check if <ul> has less than 3 <li> items and apply CSS style

I need to change the width of the ul li items, when there is less than 3 li items inside the UL. This is what I created, but it’s not working properly, can you help me fix it?

jQuery(document).ready(function($) {
  if ($('ul.products li').length <= 3) {
  $($this).css('width', '29%'); 
}})

The site is http://www.demo.simplexweb.dk/shopdemo1/ . It is related to the section with 3 products. If someone add a new products, the css should be different.

Read More

Thanks,
Tom

Related posts

Leave a Reply

1 comment

  1. you can do this with css only like so :

     li:nth-of-type(1):nth-last-of-type(2),
     li:nth-of-type(2):nth-last-of-type(1){width: 50%;}
    

    if it’s the first of it’s type and second to last of it’s type that’s means if these two condition are true so there is only two element for this type, then you can apply width: 50%;

    Live Demo

    try to add an other li element to the ul and the style will not work

    and this is exactly what you need for your task :

    li:nth-of-type(1):nth-last-of-type(2),
     li:nth-of-type(2):nth-last-of-type(1){
    
        width: 50%;
        background-color: black;
    }
    
    li:only-of-type{  // this to still apply the style if the element is only of it's type
    
        width: 50%;
        background-color: black;
    
    }
    

    Live Demo

    Now you can style the li's element inside the ul only if there is less then 3 li's without any javascript

    EDIT

    for less or equivalent to 3 li's :

     li:nth-of-type(1):nth-last-of-type(3),
     li:nth-of-type(3):nth-last-of-type(1),
     li:nth-of-type(2):nth-last-of-type(2){width: 50%; background-color: black;}
    
     li:nth-of-type(1):nth-last-of-type(2),
     li:nth-of-type(2):nth-last-of-type(1){width: 50%; background-color: black;}
    
    li:only-of-type{
    
        width: 50%;
        background-color: black;
    
    }
    

    for less or equivalent to 4 li's :

     li:nth-of-type(1):nth-last-of-type(4),
     li:nth-of-type(2):nth-last-of-type(3),
     li:nth-of-type(3):nth-last-of-type(2),
     li:nth-of-type(4):nth-last-of-type(1){width: 50%; background-color: black;}
    
     li:nth-of-type(1):nth-last-of-type(3),
     li:nth-of-type(3):nth-last-of-type(1),
     li:nth-of-type(2):nth-last-of-type(2){width: 50%; background-color: black;}
    
     li:nth-of-type(1):nth-last-of-type(2),
     li:nth-of-type(2):nth-last-of-type(1){width: 50%; background-color: black;}
    
    li:only-of-type{
    
        width: 50%;
        background-color: black;
    
    }