Hide div on mobile devices, using CSS

2020-02-05 05:34发布

I want to hide a div containing the facebook likebox widget from mobile devices. I tried this but it doesn't work.

div code:

<div id="facebook" class="fb-like-box mobile-hide" data-href="https://www.facebook.com/mypage" data-width="220" data-height="250" data-show-faces="true" data-stream="false" data-header="true"></div>

css code:

@media screen and (min-width: 0px) and (max-width: 720px) {
  #facebook { display: none; }
  .mobile-hide{ display: none; }
}

What am i doing wrong? It does not work using the id or the class reference.

10条回答
劫难
2楼-- · 2020-02-05 06:24

Make sure your page defines a viewport meta tag.

  <meta name="viewport" content="width=device-width, initial-scale=1.0">

For more information on this tag see: Understanding The Viewport Meta Tag.

查看更多
闹够了就滚
3楼-- · 2020-02-05 06:24

Okay I had this problem a while back, and for some odd reason it only worked when i put my media query rules at the end of the css. Don't know why that is, maybe a bug of some sort, but give that a try and let us know if that works.

查看更多
欢心
4楼-- · 2020-02-05 06:29

For some reason (unknown to me) this worked:

<div  class="mobile-hide">
<div class="fb-like-box" data-href="https://www.facebook.com/mypage" data-width="220" data-height="250" data-show-faces="true" data-stream="false" data-header="true"></div>
</div>
查看更多
家丑人穷心不美
5楼-- · 2020-02-05 06:31

<style type="text/css">
  .mobileShow {
    display: none;
  }
  /* Smartphone Portrait and Landscape */
  
  @media only screen and (min-device-width: 320px) and (max-device-width: 480px) {
    .mobileShow {
      display: inline;
    }
  }
</style>
<!--.mobileHide{ display: none;}-->

<style type="text/css">
  .mobileHide {
    display: inline;
  }
  /* Smartphone Portrait and Landscape */
  
  @media only screen and (min-device-width: 320px) and (max-device-width: 480px) {
    .mobileHide {
      display: none;
    }
  }
</style>

<body>
  <div class="mobileHide">
    <p>TEXT OR IMAGE NOT FOR MOBILE HERE
      <p>
  </div>
  <p> yep its working</p>
  <div class="mobileHide">
    <p>THIS SHOULD NOT SHOW On Mobile (view in mobile mode)
      <p>
  </div>
</body>

Source: https://blog.hubspot.com/marketing/site-content-only-mobile-viewers-can-see-ht

This code should work, You could also do a mobile redirect, or you can use JavaScript to detect the device (android or iPhone) though I would recommend I combination of the two and take note of screen sizes.

Other links

https://coderwall.com/p/i817wa/one-line-function-to-detect-mobile-devices-with-javascript

What is the best way to detect a mobile device in jQuery?

查看更多
登录 后发表回答