使用CSS有选择地显示内容,避免冲突

时间:2015-10-28 09:13:01

标签: html css responsive-design

我正在使用CSS根据视口大小选择性地显示内容。 E.g:

CSS:

.hires, .midres, .lowres {
  display: none;
}

@media only screen and (min-width: 801px) {     /* hires, desktop */
  .hires {
    display: inline;
  }
}

@media only screen
            and (min-width: 600px)
            and (max-width: 800px) {            /* mid res, tablet */
  .midres {
    display: inline;
  }
}

@media only screen
            and (min-width: 320px)
            and (max-width: 599px) {            /* Low res / smartphone */
  .lowres {
    display: inline;
  }
}

HTML:

<p class="hires">Resolution: high.</p>
<p class="midres">Resolution: medium.</p>
<p class="lowres">Resolution: low.</p>
<p>This paragraph will always be displayed regardless of resolution.</p>

哪个有效,但只有一点。说到图像,事实证明我在这里整齐地画了一个角落。因为在某个地方,有类似的东西:

CSS:

@media only screen
            and (min-width: 320px)
            and (max-width: 599px) {           /* Low res / smartphone */
  img {
    float: none;
    display: block;
    width: 100%;
    height: auto;
  }
}

这意味着在以下情况中:

<img src="foo.jpg" class="hires" />

无论视口大小如何,图像始终显示,因为'display:block;'覆盖(与之相冲突)前面的规则,以选择性地显示图像。

不幸的是,'display'与'none'没有对比。我无法使用“可见性”,因为这仍然会留下隐藏内容的空白。我可以使用jQuery来显示()和hide()内容,但我宁愿不将我的样式的一部分从样式表(它所属的地方)移动到Javascript(严格来说,它不会)。

不幸的是,我现在才注意到这个小麻烦,这是一个进入项目的方式。这意味着我是个白痴。 : - )

处理上述问题的最佳方法是什么?

1 个答案:

答案 0 :(得分:1)

您可以使用类别lores将图像包装在某些内容中,或者使用img.lowres作为css中的选择器,即

@media only screen
            and (min-width: 320px)
            and (max-width: 599px) {           /* Low res / smartphone */
  img.lowres {
    float: none;
    display: block;
    width: 100%;
    height: auto;
  }
}