使用@supports selector() 尽管 Sass 不支持它

Using @supports selector() despite Sass not supporting it

我想通过选择器使用新的 CSS feature queries,像这样:

:root { --focus-shadow: 0 0 0 2.4px rgba(130, 138, 145, 0.5); }

/* Focus styles even for mouse selection in old browsers */
*:focus { outline: none; box-shadow: var(--focus-shadow); }

/* Newer browsers: Only add focus styles if e.g. navigating with the keyboard */
@supports selector(*:focus-visible) {
  *:focus { box-shadow: none; }
  *:focus-visible { box-shadow: var(--focus-shadow); }
<a href="#">Focus me</a>

以上内容有效CSS(尽管 poorly supported as of June 2020), but Sass doesn't support it in either of its two implementations yet. It's in the works, but it looks like it'll take a while to implement it. Trying to compile the above through Sass throws an error (varies between Sass implementations; see these issues 有关错误的详细信息)。

与此同时,我想欺骗 Sass 按原样编译我的支持查询,而不是试图理解它。我尝试了一些失败的事情。使用unquote(),这是最有希望的尝试:

@mixin supports-selector( $selector ) {
   $query-str: #{ unquote( '@supports selector(' ) }#{ unquote( $selector ) }#{ ')' };

   #{ unquote( $query-str ) }#{ unquote( '{' ) }
      @content;
   #{ unquote( '}' ) }
}

:root { --focus-shadow: 0 0 0 2.4px rgba(130, 138, 145, 0.5); }

*:focus { outline: none; box-shadow: var(--focus-shadow); }

@include supports-selector( '*:focus-visible' ) {
    *:focus { box-shadow: none; }
    *:focus-visible { box-shadow: var(--focus-shadow); }
}

虽然 still 会引发错误,因为 Sass 期望任意字符串是 属性 后跟冒号:

property "#{ unquote( $query-str ) }#{ unquote( '{' ) }" must be followed by a ':'

不取消对 @supports 部分的引用会导致错误 selector(whatever) 不是有效的 @supports 条件。

我不知道还能尝试什么。

如何欺骗 Sass 不编译我的 mixin?

这可能对您有用 - 通过转义字符,它仍然会编译为 CSS。

SASS/SCSS 处理器挂起的不是 @supports,而是 *:focus-visible:

:root { --focus-shadow: 0 0 0 2.4px rgba(130, 138, 145, 0.5); }

/* Focus styles even for mouse selection in old browsers */
*:focus { outline: none; box-shadow: var(--focus-shadow); }

/* Newer browsers: Only add focus styles if e.g. navigating with the keyboard */
@supports #{'\(*:focus-visible)'} {
  *:focus { box-shadow: none; }
  *:focus-visible { box-shadow: var(--focus-shadow); }
}

编译为:

:root {
  --focus-shadow: 0 0 0 2.4px rgba(130, 138, 145, 0.5);
}

/* Focus styles even for mouse selection in old browsers */
*:focus {
  outline: none;
  box-shadow: var(--focus-shadow);
}

/* Newer browsers: Only add focus styles if e.g. navigating with the keyboard */
@supports (*:focus-visible) {
  *:focus {
    box-shadow: none;
  }

  *:focus-visible {
    box-shadow: var(--focus-shadow);
  }
}

SASSMEISTER Link一起玩

编辑:根据您的评论,您仍然可以添加 selector:

@supports  #{'\selector(*:focus-visible)'}  {
  *:focus { box-shadow: none; }
  *:focus-visible { box-shadow: var(--focus-shadow); }
}

Updated SASSMeister