是否可以在媒体查询中嵌套媒体查询?

问题描述:

这可能吗?这对我来说似乎是一个很好的解决方案,但我不确定它是否会起作用。是否可以在媒体查询中嵌套媒体查询?

@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 */ 

    } 

} 

您应该能够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 */ 

} 

想要做到这一点,最好的方法是在链接标记中使用高级媒体查询,然后在链接工作表中使用其他查询。

实际上,尽管大多数人将他们的CSS规则从覆盖常见内容的基本表中放回,然后在每个媒体规则集中对其进行更改。

+1

我喜欢这个主意,因为它在技术上确实嵌套为暗示。 –

我认为不可能,但你可以写这种格式如果你使用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; 
    } 
}