SASS是否支持将元素规范作为嵌套选择器?

时间:2016-10-24 18:46:52

标签: css sass

让我们说你有这个SASS定义(不真实的例子):

.class {
    margin: 1px;
    background: black;
    color: white;

    &:hover {
        color: red;
    }
}

a.class {
    margin: 1px;
    background: black;
    color: yellow;

    &:hover {
        color: blue;
    }
}

现在,我们可以将同一类的a规范作为嵌套选择器吗?例如。像这样的东西(伪代码):

.class {
    margin: 1px;
    background: black;
    color: white;

    &:hover {
        color: red;
    }

    // Some selector to show that the current class
    // should be applied to this element (?)
    a.& {
        color: yellow;

        &:hover {
            color: blue;
        }
    }
}

2 个答案:

答案 0 :(得分:5)

我有一个解决方案。它有点棘手,但它的工作正常。

<section class="test1" style="background-image: url('http://www.planwallpaper.com/static/images/cool-background.jpg');">
  <ul>
    <li>
      <h1>test1</h1>
      <li>
        <p>test</p>
      </li>
  </ul>
</section>
<section class="test2" style="background-image: url('http://www.planwallpaper.com/static/images/cool-background.jpg');">
  <ul>
    <li>
      <h1>test2</h1>
      <li>
        <p>testtest</p>
      </li>
  </ul>
</section>
<section class="test3" style="background-image: url('http://www.planwallpaper.com/static/images/cool-background.jpg');">
  <ul>
    <li>
      <h1>test3</h1>
      <li>
        <p>testtesttest</p>
      </li>
  </ul>
</section>
<section class="test4" style="background-image: url('http://www.planwallpaper.com/static/images/cool-background.jpg');">
  <ul>
    <li>
      <h1>test4</h1>
      <li>
        <p>testtesttesttest</p>
      </li>
  </ul>
</section>
<section class="test5" style="background-image: url('http://www.planwallpaper.com/static/images/cool-background.jpg');">
  <ul>
    <li>
      <h1>test5</h1>
      <li>
        <p>testtesttesttesttest</p>
      </li>
  </ul>
</section>
<section class="test6" style="background-image: url('http://www.planwallpaper.com/static/images/cool-background.jpg');">
  <ul>
    <li>
      <h1>test6</h1>
      <li>
        <p>testtesttesttesttesttest</p>
      </li>
  </ul>
</section>

<强> Working Fiddle

答案 1 :(得分:1)

你可以考虑写一个mixin

  @mixin sample($color,$hovercolor) {
      margin: 1px;
    background: black;
    color: $color;

    &:hover {
        color: $hovercolor;
    }
  }

    .class{ @include sample(white,red)}
    a{ @include sample(yello,yellow)}

希望这有帮助