2015-10-28 29 views
0

我使用CSS根據視口大小選擇性地顯示內容。例如: -使用CSS選擇性地顯示內容,避免衝突

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'與'none'沒有任何相反之處。我無法使用「可見性」,因爲這仍然會在隱藏的內容之前留下空隙。我可以使用jQuery來顯示()和隱藏()內容,但我寧願將樣式表的一部分從樣式表(它所屬的位置)移至Javascript(嚴格來說,它不會)。

不幸的是,我現在才注意到這個小小的混亂,這個項目很不錯。這意味着我是個白癡。 :-)

處理上述問題的最佳方法是什麼?

+0

道歉,如果我有誤解,但你說,'IMG {顯示:塊;}'已經過了統治'.hires {display:none;}'?這不應該是這種情況,因爲'.hires'比'img'更具體,所以其他的東西可能在這裏。你能否提供你正面臨的確切問題的可重現的例子? –

+0

你是說'display:none'在圖像上不起作用嗎? –

+1

這裏的問題究竟是什麼? http://jsfiddle.net/hjq0hthc/ –

回答

1

你既可以換圖片的東西與類洛雷斯或使用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; 
    } 
} 
+0

閱讀本文後,我意識到我省略了一些內容,不管視口大小如何,都應該總是顯示內容。這意味着上述內容適用於我的初始示例,但不適用於更正的示例。我的錯。 –

+0

@FrankvanWensveen它仍然適用於更正後的示例。 img.lowres比img更具體 – Luciano