Select parent 选择器 SASS/SCSS

Select parent selector in SASS/SCSS

我对 SCSS 语法有一点误解。使用 BEM 方法创建小组件并在 SCSS 中遇到问题。 HTML:

<div class="message message--success">
        <div class="message__title">
          BEM Example
        </div>
        <div class="message__content">
          <p>BEM Example text</p>
        </div>
      </div>

SCSS:

.message {
  display: block;
  width: 300px;
  border-radius: 5px;
  border: 2px solid #000;
  padding: 10px;

  &__title {
    font-size: 18px;
    line-height: 1;
    color: #000;
    margin-bottom: 10px;
  }

  &__content {
    font-size: 15px;
    color: #000;
  }

  &--success {
    border-color: #3f9442;

    &__title {
      color: #3f9442;
    }

    &__content {
      color: #3f9442;
    }
  }
}

如您所见,我有 .message--success class 和内部 &--success 直接样式(border-color)的作品,但不是标题和内容的样式。如何 select .message* as parent for **&__title and &__content里面&--成功

要么用完整的 class 名称编写两个选择器(不使用 &),要么保存对 .message class 的引用并使用它在嵌套选择器中

.message {

  display: block;
  width: 300px;
  border-radius: 5px;
  border: 2px solid #000;
  padding: 10px;

  $this: &; /* reference to the .message class */

  &__title {
    font-size: 18px;
    line-height: 1;
    color: #000;
    margin-bottom: 10px;
  }

  &__content {
    font-size: 15px;
    color: #000;
  }

  &--success {
    border-color: #3f9442;

    /* use the reference stored */

    #{$this}__title {
      color: #3f9442;
    }

    #{$this}__content {
      color: #3f9442;
    }
  }
}

试试这个方法

.message {
  display: block;
  width: 300px;
  border-radius: 5px;
  border: 2px solid #000;
  padding: 10px;

  &__title {
    font-size: 18px;
    line-height: 1;
    color: #000;
    margin-bottom: 10px;
  }

  &__content {
    font-size: 15px;
    color: #000;
  }

  &--success {
    border-color: #3f9442;
    .message{
      &__title {
        color: #3f9442;
      }

      &__content {
        color: #3f9442;
      }
    }
  }
}

https://jsfiddle.net/lalji1051/21b3cksm/4/