为什么我的DIV没有在手机上展示?

时间:2016-03-14 09:16:10

标签: html css

我试图根据屏幕分辨率显示/隐藏HTML代码。 我可以在台式电脑上看到DIV news_box_desktop ,但我的手机上根本看不到任何DIV(而 news_box_mobile 应该可见) 有什么问题? 谢谢,

HTML:

<header class="clearfix">
  <a href="index.html" title=""><img class="logo" src="images/blue.png" alt=""></a>
  <div class="menu-container">
    <nav>
      <ul id="menu">
        <li> <a href="index.html">Accueil</a> </li>
        <li class="selected"> <a href="biographie.html">Biographie</a> </li>
      </ul>
    </nav>
  </div>
  <div id="news_box" class="news_box_desktop" style="position: absolute; bottom:20px; right: 20px; width: 380px; float: right; text-align: left;"></div>
</header>
<div id="news_box" class="news_box_mobile" style="position: relative; width: 90%; margin:auto; left: 0; right: 0; text-align: left;"></div>

CSS:

@media only screen and (max-width: 40em) {
.news_box_desktop {
    display: none;
}
.news_box_mobile {
    display: block;
}
    }

2 个答案:

答案 0 :(得分:0)

试试这个:

@media only screen and (max-width: 40em) {
.news_box_desktop {
    display: none;
}
.news_box_mobile {
    display: block;
}
}

@media only screen and (min-width: 40em) {
.news_box_mobile {
    display: none;
}
.news_box_desktop {
    display: block;
}
}

在这里jsbin,我已在手机中查看了它的输出。

答案 1 :(得分:0)

您需要进行以下更改才能使其正常运行。

header {
  position: relative;       /* so you desktop show inside header */
}
.news_box_mobile {
  display: none;            /* so your mobile is hidden by default */
}

我还建议您将所有CSS外部(我在下面的示例中为您完成),因为它将带来更简单的维护,重用规则和更清晰的标记。

header {
  position: relative;       /* so you desktop show inside header */
}
.news_box_mobile {
  display: none;            /* so your mobile is hidden by default */
  position: relative;
  width: 90%;
  margin:auto;
  left: 0;
  right: 0;
  text-align: left;
}

.news_box_desktop {
  position: absolute;
  bottom:20px;
  right: 20px;
  width: 380px;
  float: right;
  text-align: left;
}


@media only screen and (max-width: 40em) {
  .news_box_desktop {
    display: none;
  }
  .news_box_mobile {
    display: block;
  }
}
<header class="clearfix">
  <a href="index.html" title=""><img class="logo" src="images/blue.png" alt=""></a>
  <div class="menu-container">
    <nav>
      <ul id="menu">
        <li> <a href="index.html">Accueil</a> </li>
        <li class="selected"> <a href="biographie.html">Biographie</a> </li>
      </ul>
    </nav>
  </div>
  <div id="news_box" class="news_box_desktop">desktop</div>
</header>
<div id="news_box" class="news_box_mobile">mobile</div>