How To Add Class Depending On Media Screen Size

On our site, we wanted to control how many columns were displayed and where the sidebar was positioned depending on the user’s screen size.   The best approach was to add or remove a stylesheet class using jQuery.  We added the following code to our custom.js file, but it could also be added to footer.php.

We targeted our container div (with the id=”Page”), and added or removed the class “screen” or “mobile” depending on screen size.  You could also apply it to the body by replacing #page with body (no quotes).

jQuery(document).ready(function($) {
//  https://codepen.io/richerimage/pen/jEXWWG
  var alterClass = function() {
    var ww = document.body.clientWidth;
    if (ww < 768) {
      $('#page').removeClass('screen');
      $('#page').addClass('mobile');
    } else if (ww >= 768) {
      $('#page').addClass('screen');
      $('#page').removeClass('mobile');
    };
  };
  $(window).resize(function(){
    alterClass();
  });
  //Fire it when the page first loads:
  alterClass();
});

To add the jQuery to your footer.php file, wrap the code in <script>…</script> tags.

To use a custom .js file, save the code in a file and then add the following code to your child theme functions.php file.

// Add Custom Scripts
wp_register_script( 'Custom', get_template_directory_uri().'/custom.js', null, null, true );
wp_enqueue_script('Custom');

You can now apply different styles to your site depending on browser size.  Just add the desired style definitions to your style.css file.

.screen {
    background-color: #ffffff;
}
.mobile {
    background-color: #e5e5e5;
}

Using this method, you can control positioning of elements such as your sidebar, or hide elements altogether.