Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/css/41.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/powerbi/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Css 如何在SASS中将样式应用于类和媒体查询?_Css_Sass_Dry - Fatal编程技术网

Css 如何在SASS中将样式应用于类和媒体查询?

Css 如何在SASS中将样式应用于类和媒体查询?,css,sass,dry,Css,Sass,Dry,在移动设备上,我的标题必须始终是粘性的。在其他设备上,只有当它具有类sticky时,它才必须是粘性的: .header { &.sticky { position: fixed; // other styles } } @media only screen and (max-width: 600px) { .header { position: fixed; // other styles } } 我只想写一次我的风格(枯燥的原则),有

在移动设备上,我的标题必须始终是粘性的。在其他设备上,只有当它具有类
sticky
时,它才必须是粘性的:

.header {
  &.sticky {
    position: fixed;
    // other styles
  }
}

@media only screen and (max-width: 600px) {
  .header {
    position: fixed;
    // other styles
  }
}
我只想写一次我的风格(枯燥的原则),有没有办法通过
SASS
来实现这一点

它可能看起来像:

.header {
  @include media_600,
  &.sticky {
    position: fixed;
  }
}

。。或者类似的事情,但我不知道是什么。

我认为你的思路是对的。使用内容块()创建mixin将允许您添加样式,而无需再次指定选择器,还将允许您在整个代码中重用它

@mixin mobile {
  @media only screen and (max-width: 600px) {
    @content;
  }
}

.header {
  &.sticky {
    position: fixed;
  }

  @include mobile { 
    position: fixed;
  }
}
如果您只想编写CSS属性一次,那么您可以这样做

@mixin sticky-header {
  position: fixed;
}

.header {
  &.sticky {
    @include sticky-header;
  }

  @media only screen and (max-width: 600px) { 
    @include sticky-header;
  }
}

也许有一种方法可以使用SASS以某种方式将其归档,但DRY并不意味着永远不允许复制某些代码。因为不管采用哪种解决方案,理解代码中发生的事情都会困难得多(想想KISS原则)。另外,不管您做什么,编译后的CSS代码看起来都像您的示例。您可以做的是,将
@仅媒体屏幕和(最大宽度:600px)
移动到
.header
类中,这至少会删除一点冗余。您好,虽然只使用代码回答是可以的,但建议您简要说明您的解决方案以及您做出选择的原因。@HenryWoody,谢谢你的反馈。我已经为解决方案添加了一个解释。嗯,但是你仍然需要写两次样式。。。也许我应该更明确地回答我的问题:我的目标是写一次而不是两次。@drake035我更新了答案,如果这是你想要实现的,请告诉我。