2016-09-29 71 views
2

将媒体查询嵌套到元素中可以吗?如果我想在其他地方使用min-width: 480px,会有巨大的重复。请看我的代码示例。或者只是用旧的方式?任何想法?SASS媒体查询最佳做法?

SASS

.navbar { 
    height: 500px; 
    width: 500px; 

    @media screen and (min-width: 480px) { 
     background-color: lightgreen; 
    } 
} 

.items { 
    padding: 15px; 
    color: red; 

    @media screen and (min-width: 480px) { 
     border: 1px solid black; 
    } 
} 

CSS

@media screen and (min-width: 480px) { 
    .navbar { 
     background-color: lightgreen; 
    } 

    .items { 
     border: 1px solid black; 
    } 
} 
+0

真的取决于项目海事组织。对于较小的项目,只要它是可读的,我相信最初的一个是可以的。但对于最佳做法,我会使用“旧”的方式来定义媒体查询。你可能想看看ITCSS – adamk22

+0

伊莫这绝对是最好的方式。为了避免“巨大的重复”,为什么不把'min-width:480px'存储为变量? '@media屏幕和($分辨率 - 小){...}'或其他... –

+0

@EdmundReed:但它也在重复媒体查询语句。 – Janath

回答

0
$pc: 1024px; // PC screen size. 
$tablet: 720px; // Tablet screen size. 
$phone: 320px; // Phone screen size. 

@mixin responsive($media) { 
    @if $media= phone { 
    @media only screen and (max-width: $tablet - 1) { 
     @content; 
    } 
    } 
    @else if $media= tablet { 
    @media only screen and (min-width: $tablet - 1) and (max-width: $pc) { 
     @content; 
    } 
    } 
    @else if $media= pc { 
    @media only screen and (min-width: $pc + 1) and (min-width: $pc) { 
     @content; 
    } 
    } 
    @else if $media= pc_tablet { 
    @media only screen and (min-width: $tablet - 1) { 
     @content; 
    } 
    } 
} 

例子

body { 
    @include responsive(pc) { 
    background: red; 
    } 
    @include responsive(tablet) { 
    background: yellow; 
    } 
    @include responsive(phone) { 
    background: green; 
    } 
}