我有两个媒体查询。一种用于手机,另一种用于平板电脑。他们都要求完全相同的样式。在这种情况下,保留此代码的最佳方法是什么 DRY ?
$mobile-portrait: "only screen and (max-width: 680px)";
$tablet-portrait: "only screen and (min-device-width : 768px) and (max-device-width : 1024px) and (orientation : portrait)";
div {
background: gray; margin: 0 auto; height: 50px; width: 50px;
@media #{$mobile-portrait} {
height: 100px; width: 100px;
}
@media #{$tablet-portrait} {
height: 100px; width: 100px;
}
}
最佳答案
我不确定是否有任何好的方法可以做到这一点,但您始终可以创建多个选择器。 (我不知道这是否是最佳实践,但这就是我会做的。)
<罢工>罢工>
<罢工>@media #{$mobile-portrait},
@media #{$tablet-portrait} {
height: 100px;
width: 100px;
}
编辑:以下内容也有效。
@media #{$mobile-portrait}, @media #{$tablet-portrait} {
height: 100px; width: 100px;
}
罢工><罢工>罢工>
为了美观,我更喜欢将选择器放在多行上。当选择器较长时,换行符有助于区分它们。
我也更喜欢多行样式。如果选择器中有超过三到四个,可能会变得困惑。
编辑2:逗号实际上就像一个逻辑or
当在媒体查询内部时。
根据这个MDN article :
comma-separated lists
Comma-separated lists behave like the logical operator
or
when used in media queries. When using a comma-separated list of media queries, if any of the media queries returns true, the styles or style sheets get applied. Each media query in a comma-separated list is treated as an individual query, and any operator applied to one media query does not affect the others. This means the comma-separated media queries can target different media features, types, and states.
这意味着第二个 @media
没有必要:
@media #{$mobile-portrait}, #{$tablet-portrait} {
height: 100px;
width: 100px;
}
关于html - 使用媒体查询保持 SASS 代码干燥,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22903576/