2011-10-05 146 views
24

這可能嗎?這對我來說似乎是一個很好的解決方案,但我不確定它是否會起作用。是否可以在媒體查詢中嵌套媒體查詢?

@media only screen 
and (min-device-width : 320px) 
and (max-device-width : 480px) { 

    /* Code for both portrait and landscape */ 

    @media (orientation:portrait) { 

     /* Code for just portrait */ 

    } 

    @media (orientation:landscape) { 

     /* Code for just landscape */ 

    } 

} 

回答

27

您應該能夠nest @media rules this way in CSS3,但它尚未被大多數瀏覽器支持。詳情請參閱this answer

你將不得不全面擴大和重複頂級媒體查詢的內部規則,它跨瀏覽器工作(和我想象中的SCSS處理器將產生類似的東西):如果你

@media only screen 
and (min-device-width: 320px) 
and (max-device-width: 480px) { 
    /* Code for both portrait and landscape */ 
} 

@media only screen 
and (min-device-width: 320px) 
and (max-device-width: 480px) 
and (orientation: portrait) { 

    /* Code for just portrait */ 

} 

@media only screen 
and (min-device-width: 320px) 
and (max-device-width: 480px) 
and (orientation: landscape) { 

    /* Code for just landscape */ 

} 
2

想要做到這一點,最好的方法是在鏈接標記中使用高級媒體查詢,然後在鏈接工作表中使用其他查詢。

實際上,儘管大多數人將他們的CSS規則從覆蓋常見內容的基本表中放回,然後在每個媒體規則集中對其進行更改。

+1

我喜歡這個主意,因爲它在技術上確實嵌套爲暗示。 –

0

我認爲不可能,但你可以寫這種格式如果你使用SASS css預處理器。

例如,您可以將此代碼複製並粘貼到https://www.sassmeister.com/ - 和觀察輸出

SASS

@media only screen and (max-width: 767px) { 
    body{ 
    color:red; 
    } 
    @media (orientation:portrait) { 
     body{ 
     color:green; 
     } 
    } 
    @media (orientation:landscape) { 
     body{ 
     color:orange; 
     } 
    } 
} 

輸出CSS

@media only screen and (max-width: 767px) { 
    body { 
    color: red; 
    } 
} 
@media only screen and (max-width: 767px) and (orientation: portrait) { 
    body { 
    color: green; 
    } 
} 
@media only screen and (max-width: 767px) and (orientation: landscape) { 
    body { 
    color: orange; 
    } 
}