Apply Different CSS Styles Based On Window Size (Responsively) Without Using JavaScript Window Event

Switching CSS classes or properties based on screen size can be achieved using JavaScript as shown below. But handling such things with JavaScript window resize event is not as efficient to achieve it with CSS.

$(window).on('resize', function() {
    if($(window).height() > 400) {
        $('#body').addClass('your-class');
        $('#body').removeClass('your-class');
    }else{
        $('#body').addClass('your-class-2');
        $('#body').removeClass('your-class-2');
    }
})

Using Tailwind

For example, if we want to create a feature where the child menu opens on mouseenter event and closes on mouseleave. But we only want to achieve this on desktop not on mobile. Let’s see how Tailwind helps us achieve it.

Let’s create two utility classes in Tailwind:

@layer utilities {
   @responsive {

      .wp-sm-hidden {
         display: none;
         @screen lg {
            display: block;
         }
      }

      .wp-lg-hidden {
         display: block;
         @screen lg {
            display: none;
         }
      }
   }
}

Now in our HTML code

<ul>
<li>
   <a class="parent-menu-item" href="#">Parent Menu item</a>
   <ul class="child-menu wp-sm-hidden lg:wp-lg-hidden>
     Child menu
   </ul>
</li>
</ul>

The JavaScript

const parentMenuItem = $('.parent-menu-item');
const childMenu = $('.child-menu');
parentMenuItem.on( 'mouseenter', ( event ) => openChildMenu( event ) );
parentMenuItem.on( 'mouseleave', ( event ) => closeChildMenu( event ) );
function openChildMenu( event ) {
   childMenu.removeClass( 'lg:wp-lg-hidden' );
}
function closeChildMenu( event ) {
   childMenu.addClass( 'lg:wp-lg-hidden' );
}

Explanation

Now the class `lg:wpr-lg-hidden` will be applied on mouseenter on both desktop and mobile, but because there is a prefix lg: before the class name wp-lg:hidden the CSS properties will only be applied in the desktop and not on mobile and that solves our problem.

That’s all folks!

Leave a Reply