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

问题描述 投票:0回答:1

在移动设备上,我的标题必须始终是粘性的。在其他设备上,仅当它具有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;
  }
}

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

css sass dry
1个回答
0
投票

我认为您在正确的轨道上。创建带有内容块(https://sass-lang.com/documentation/at-rules/mixin)的mixin将使您可以添加样式而不必再次指定选择器,还可以使您在整个代码中重复使用它。

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

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

  @include mobile { 
    position: fixed;
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.