简体   繁体   中英

Show a div only on small screens with jquery or css

I want to show this html code, only on small screens.

<div id="NightDiv" class="w3-center" style="padding-top:20px"><i id="nightMode2" class="fa fa-moon-o fa-lightbulb-o w3-cursor-pointer w3-amazon"  aria-hidden="true"></i>
</div>

This is what I am trying with no success:

$(document).ready(function() {

if ((screen.width>=1024) ) {
 $("#NightDiv").hide();
}
else {
 $("#NightDiv").show();

}
});

You don't need JavaScript for this. Use CSS Media Query to do this,

/*Hide for larger screens*/
#NightDiv {
   display: none;
}

/*show for small screens */
@media screen and (max-width: 1023px) { /* I've given 1023px but you can change to proper width */
    #NightDiv {
        display: block;
    }
}

This is better handled by CSS media queries. See sample below: (expand the snippet to hide the div)

 //no javascript! 
 .w3-center { display: none; /* hide by default */ } @media(max-width:1024px){ .w3-center { display: block; /* or inline, or whichever style you prefer*/ } } 
 <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css" rel="stylesheet"/> <div id="NightDiv" class="w3-center" style="padding-top:20px"><i id="nightMode2" class="fa fa-moon-o fa-lightbulb-o w3-cursor-pointer w3-amazon" aria-hidden="true"></i> </div> 

<div id="NightDiv" class="w3-center" style="padding-top:20px">
    <i id="nightMode2" class="fa fa-moon-o fa-lightbulb-o w3-cursor-pointer w3-amazon"  aria-hidden="true"></i>
</div>

<style>
    #NightDiv{
        display: none;
    }
    @media only screen and (max-width:768px{
        #NightDiv{
            display: block;
        }
    }
</style>

 ShowDiv(); $(window).resize(function() { ShowDiv(); }); function ShowDiv(){ if (window.innerWidth>=1024 ) $("#NightDiv").hide(); else $("#NightDiv").show(); } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="NightDiv" class="w3-center" style="padding-top:20px;width:200px;height:100px;background-color:pink;"><i id="nightMode2" class="fa fa-moon-o fa-lightbulb-o w3-cursor-pointer w3-amazon" aria-hidden="true"></i> </div> 

Try this code

 jQuery(document).ready(function () {
        jQuery('#NightDiv').hide();
        // Display the div on mobile resoultions
        if (jQuery(window).width() < 700) {
            jQuery('#NightDiv').show();
        }
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM