css - 如何将样式应用于 SASS 中的类和媒体查询?

标签 css sass dry

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

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

@media only screen and (max-width: 600px) {
  .header {
    position: fixed;
    // other styles
  }
}

我只想写一次样式(DRY 原则),有没有办法用 SASS 实现?

它可能看起来像:

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

.. 或类似的东西,但我不知道是什么。

最佳答案

我认为您走在正确的轨道上。使用内容 block ( https://sass-lang.com/documentation/at-rules/mixin#content-blocks ) 创建混合将允许您添加样式而无需再次指定选择器,还可以让您在整个代码中重用它。

@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;
  }
}

关于css - 如何将样式应用于 SASS 中的类和媒体查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58674489/

相关文章:

css - PhpStorm 中的文件观察器编译速度太快

javascript - 如何为多次呈现的部分使用一个 html 代码

c# - 像在 Ruby 中一样在 C# 中使用 yield

jquery - 如何更改下个月/上个月箭头的颜色(jQuery Datepicker)

HTML:如何使用 CSS 作为链接样式表添加图像

css - ie7 & 6 烦人的样式问题

css - scaleX(0) 正在占用宽度

html - 位置 : absolute styling only works if I use pos: absolute

php - Codeigniter 如何设置 API key 和资源 URL 以便在应用程序中轻松访问

html - 在 SELECT OPTION 中左对齐一个词,右对齐一个词