【问题标题】:How to select parent pseudo-class from within child using scss如何使用 scss 从子级中选择父级伪类
【发布时间】:2017-12-18 17:19:49
【问题描述】:

我想使用以下模式选择父级。

我知道我可以在父选择器中写这个,但我想知道是否可以在子选择器中为子选择器添加父伪类的前缀。

JSX:

<div class="parent">
    <div class="child" />
</div>
<div class="parent">
    <div class="child" />
</div>

SCSS:

.parent {
    height: 100px;

    .child {
    // the goal is to write this so it produces the CSS output below, from 
    // within .child

        &:first-child & {
            height: 50px;
        }
    }
}

CSS [输出]:

.parent:first-child .child {
    height: 50px;
}

【问题讨论】:

  • 尽管找到了解决方案,但我仍然很想知道是否有办法在不重写子类中的父类名称的情况下做到这一点。

标签: css sass ampersand


【解决方案1】:

也许不是最有用的代码,但有效:

SASS

.parent {
  $root: &;
  height: 100px;
  @at-root {
    .child {
      @at-root {
        #{$root}:first-child #{&} {
          height: 50px;
        }
      }
    }
  }
}

输出

.parent {
  height: 100px;
}
.parent:first-child .child {
  height: 50px;
}

【讨论】:

  • 感谢分享
【解决方案2】:

看来这真的很容易。哎呀。

您只需执行以下操作:

SCSS:

.child {
    .parent:first-child & {
        height: 50px;
    }
}

这可能看起来很傻,但对于我的情况,它实际上很有用。

【讨论】:

  • 你可以在 sass 中做到这一点非常酷,感谢您提供解决方案。但是,我会避免在生产中使用这种做法,因为它可能会变得难以阅读和维护。
猜你喜欢
  • 2021-05-14
  • 1970-01-01
  • 1970-01-01
  • 2011-03-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多