html - 使用媒体查询保持 SASS 代码干燥

标签 html css sass media-queries

我有两个媒体查询。一种用于手机,另一种用于平板电脑。他们都要求完全相同的样式。在这种情况下,保留此代码的最佳方法是什么 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/

相关文章:

javascript - 试图用 jQuery 隐藏()一个元素

html - 当我在 body 元素中将 margin 属性设置为零时,我得到了错误的背景

html - 如何在保持 Bootstrap Grid 的同时在可变文本高度下对齐图像?

css - 如何仅缩放背景图像

css - Sass 变量更改为 css 变量?

html - 请帮我在页面加载时按顺序临时更改菜单项的颜色

javascript - 在 Javascript 中创建表时出现问题

javascript - scrollTo 函数在 JSfiddle 中运行流畅但在我的页面上运行不流畅

css - 如何突出显示表中除父行之外的行?

css - Bootstrap 4 响应式按钮大小