Hide div if screen is smaller than a certain width

dzul picture dzul · Nov 28, 2010 · Viewed 113.1k times · Source

I want to hide a floating div if the user screen is < 1024px as it will overlay with my blog content area. I found this jQuery on the net but I am not sure how to use it.

$(document).ready(function() {

if ((screen.width>1024)) {
    // if screen size is 1025px wide or larger
    $(".yourClass").css('display', 'none'); // you can also use $(".yourClass").hide();
}
elseif ((screen.width<=1024))  {
    // if screen size width is less than 1024px
    $(".yourClass").css('display', 'block'); // here you can also use show();
}
});

If my floating div class name is sharecontent, should I replace the above script like below? If yes, it's not working.

$(document).ready(function() {

if ((screen.width>1024)) {
    // if screen size is 1025px wide or larger
    $(".sharecontent").css('display', 'none'); // you can also use $(".yourClass").hide();
}
elseif ((screen.width<=1024))  {
    // if screen size width is less than 1024px
    $(".sharecontent").css('display', 'block'); // here you can also use show();
}
});

I also tried replacing the screen.width with window.width but still no success :(

Answer

Eric picture Eric · Nov 28, 2010

Use media queries. Your CSS code would be:

@media screen and (max-width: 1024px) {
    .yourClass {
        display: none !important;
    }
}