【问题标题】:Sass conditional ampersandSass 条件与符号
【发布时间】:2017-10-18 18:39:11
【问题描述】:

我有一些看起来像这样的 sass

.activities {
  border: 1px solid green;

  .activity {
    background-color: red;

    &:first-child {
      background-color: yellow;
    }
  }  
}

我希望作为第一个子元素的 .activity 元素只有在具有 .activities 类的父元素也没有类 .events 时才为黄色。

在下面的示例中,第一个 .activity 元素应该有 background-color: red

<div class="activities events">
  <div class="activity">one</div>
  <div class="activity">two</div>
  <div class="activity">three</div>
</div>

当具有.activities 的元素也具有.events 时,是否有一种DRY 方法来否定这种第一个子样式?

或者这是最简单的方法:

.events .activity:first-child {
  background-color: red;
}

【问题讨论】:

  • 我认为最底层的方式是最简单/最干的。您也可以使用 :not 选择器,但这会更复杂。

标签: css sass


【解决方案1】:

当活动元素没有事件类时,使用:not 选择器应用黄色背景。

.activities {
    border: 1px solid green;

    .activity {
        background-color: red;
    }

    &:not(.events) {
        .activity:first-child {
            background-color: yellow;
        }
    }  
}

这种方法有助于减少重复。如果你突然决定活动应该是蓝色而不是红色,你只需要在一个地方改变它,而不是两个。

https://developer.mozilla.org/en/docs/Web/CSS/:not

【讨论】:

    【解决方案2】:

    我很无聊,想看看我是否可以将所有 activity 样式保留在一个 activity 孩子中并想出了这个 - 尽管我不建议在 Nathan 的答案中使用它,因为这确实是一个毫无意义的过度解决方案:

    .activities {
      border: 1px solid green;
    
      .activity {
        background-color: red;
    
        &:first-child {
          @at-root #{selector-replace(&, '.activities', '.activities:not(.events)')} {
            background-color: yellow;
          }
        }
      }
    }
    

    如果您不想重复“活动”类,可以将其缓存为变量:

    .activities {
      $this: &;
    
      border: 1px solid green;
    
      .activity {
        background-color: red;
    
        &:first-child {
          @at-root #{selector-replace(&, $this, '#{$this}:not(.events)')} {
            background-color: yellow;
          }
        }
      }
    }
    

    Sass 是不是走得太远了?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-09-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-22
      • 2015-05-18
      • 1970-01-01
      • 2011-03-31
      相关资源
      最近更新 更多