How to select parent pseudo-class from within child using scss

╄→гoц情女王★ 提交于 2021-01-21 09:16:30

问题


I'd like to select the parent using the following pattern.

I understand I could write this within the parent selector, but I'd like to know if it's possible to prefix the parent's pseudo class to the child from within the child selector.

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 [output]:

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

回答1:


Maybe isn't the most useful code but works:

SASS

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

OUTPUT

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



回答2:


So seems like this is really easy. Whoops.

You just do the following:

SCSS:

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

This probably looks silly, but for my situation, it's actually useful.



来源:https://stackoverflow.com/questions/45088859/how-to-select-parent-pseudo-class-from-within-child-using-scss

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!