【问题标题】:How can you use multiple variable breakpoints for media queries in Stylus?如何在 Stylus 中使用多个变量断点进行媒体查询?
【发布时间】:2019-03-12 09:53:23
【问题描述】:

现状

我有以下手写笔代码

$mobile = '(max-width 767px)';
$tablet = '(min-width 768px) and (max-width: 1365px)';
$desktop = '(min-width: 1366px)';

  .sidebar
    width 300px;

    @media $tablet
      display none;

此代码运行良好 - 列出的屏幕尺寸的侧边栏消失。

问题

现在,我想让它在 $mobile 断点处消失。

理想情况下,我想要的是这样的:

$mobile = '(max-width 767px)';
$tablet = '(min-width 768px) and (max-width: 1365px)';
$desktop = '(min-width: 1366px)';

  .sidebar
    width 300px;

    @media $tablet, $mobile
      display none;

它会输出(或类似的东西)

.sidebar { width: 300px; }
@media (min-width: 768px) and (max-width: 1365px), (max-width: 767px) {
  .sidebar { display: none; }

我尝试过的

  • @media $tablet, $mobile 导致 Stylus 输出 @media $tablet, $mobile
  • @media '{$tablet}, {$mobile} 导致语法错误。
  • @media join(',', $tablet, $mobile) 导致语法错误。

我能做但不想做的事

  • 我可以设置一个新的断点$mobileAndTablet,这会破坏目的(我不想进行所有组合)。
  • 我可以在$desktop 断点上始终设置display: nonedisplay: block,这不是我要在这里寻找的(在这个例子中我有3 个断点,在其他的我可能有更多)。

TL;DR

如何在 Stylus 中为多个断点使用多个变量?

Sass 的 @media #{$mobile}, #{$tablet} 具有此功能。我正在为 Stylus 寻找类似的东西。

【问题讨论】:

  • 我希望有一些东西不会让我需要对项目中使用媒体查询的每个文件进行导入。但如果这是唯一的方法,它会做的。仍在寻找更好的方法,谢谢:)

标签: css stylus


【解决方案1】:

可能不是最好的解决方案,但您可以考虑使用for 通过编写如下代码来实现:

$mobile = '(max-width 767px)';
$tablet = '(min-width 768px) and (max-width: 1365px)';
$desktop ='(min-width: 1366px)'; 

  .sidebar
    width 300px;

    for m in $mobile $tablet
      @media m
        display none;  

你会得到这个输出:

.sidebar {
    width: 300px;
}

@media (max-width: 767px) {
    .sidebar {
        display: none;
    }
}

@media (min-width: 768px) and (max-width: 1365px) {
    .sidebar {
        display: none;
    }
}

手写笔代码与您想要的一样,但输出不会是单个媒体查询。

更新

这是另一种避免媒体查询重复的hacky方法,但您必须复制选择器:

$mobile = '(max-width: 767px)';
$tablet = '(min-width: 768px) and (max-width: 1365px)';
$desktop ='(min-width: 1366px)';

  .sidebar
    width 300px;

  unquote("@media " + join(',',$mobile $tablet) + "{")
  .sidebar
    display none;   
  unquote("}")

上面会产生这个:

.sidebar {
    width: 300px;
}

@media (max-width: 767px),(min-width: 768px) and (max-width: 1365px) {
    .sidebar {
        display: none;
    }
}

【讨论】:

    【解决方案2】:

    您将不得不丢失括号,因为手写笔将媒体查询强制插入括号以进行内联连接(手写笔不再处于积极开发中,因此这可能无法解决)以便内联工作,或者您可以只进行常规连接进入一个新变量,然后使用它。 Here is a playground

    $mobile = 'max-width: 767px'
    $laptop = 'min-width: 1366px'
    
    @media ({$mobile}) , ({$laptop})
      body
        color: green;
    

    【讨论】:

    • 知道如何处理查询由两个或多个条件形成的情况,例如他的示例?
    【解决方案3】:

    您可以使用join() 函数预先生成所需的文字:

    $media = join(',', $tablet $mobile);
    

    然后使用它:

    @media $media
        display: none;
    

    【讨论】:

    • 感谢您的回答!这类似于我说过要避免的 $mobileAndTable 解决方案,如果我有 5 个断点,那么设置所有可能的组合会很痛苦。
    猜你喜欢
    • 2012-10-15
    • 2018-05-02
    • 2017-04-12
    • 1970-01-01
    • 2016-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-25
    相关资源
    最近更新 更多