我可以检查父元素在 sass 中有特定的 class 吗?

Can I check parent element has specific class in sass?

如果父元素具有特定的 class,我想有条件地赋值。 Exp:

HTML

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

CSS

.child {
    font-size: 16px;
}

但是如果父元素有一个名为 "big"

的 class

HTML

<div class="parent big">
    <div class="child">Some Text</div>
</div>

我想按如下方式更改值

CSS

.child {
    font-size: 20px;
}

例如如下:

.child {
  font-size: parent.hasClass('big') ? 20px : 16px;
}

我如何在 SASS 中做到这一点?

只需创建两条规则:

.child {font-size: 16px;}
.big .child {font-size: 20px;}

在SASS中会是

.child
    font-size: 16px

    .big &
        font-size: 20px

使用纯CSS是不可能的(整个思路是级联的)。但是可能有一种使用 SASS 的方法。看看这个:

http://thesassway.com/intermediate/referencing-parent-selectors-using-ampersand

编辑:另一种选择是使用 JavaScript,就像 Jpegzilla 建议的那样。

CSS 中没有 parent 个选择器。您可以做的是在 parent class 上设置 font-size 并让 children 继承它。

.parent {
    font-size: 16px;

    &.big {
        font-size: 20px;
    }
}

.child {
    font-size: inherit;
}

或者你可以使用CSS变量(如果你不需要太担心IE的话)

--font-size: 16px;

.big {
    --font-size: 20px;
}

.parent {
    font-size: var(--font-size);
}

.child {
    font-size: inherit;
}

希望对您有所帮助:)