【问题标题】:Can I check parent element has specific class in sass?我可以检查父元素在 sass 中有特定的类吗?
【发布时间】:2019-03-29 17:47:10
【问题描述】:

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

HTML

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

CSS

.child {
    font-size: 16px;
}

但是如果父元素有一个名为“big”的类

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 中做到这一点?

【问题讨论】:

    标签: css if-statement sass conditional ternary-operator


    【解决方案1】:

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

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

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

    【讨论】:

    • 是的,知道了。我的意思是使用纯 css 来处理父元素是不可能的。
    • 谢谢!修复了
    【解决方案2】:

    CSS 中没有父选择器。你可以做的是在你的父类上设置你的字体大小并让孩子继承它。

    .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;
    }
    

    希望有帮助:)

    【讨论】:

    • 在 SASS (scss) 中有 are 父选择器。这就是 OP 提出的问题。
    【解决方案3】:

    只需创建两条规则:

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

    在 SASS 中是

    .child
        font-size: 16px
    
        .big &
            font-size: 20px
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-12-02
    • 1970-01-01
    • 2014-06-16
    • 2013-03-14
    • 1970-01-01
    • 2022-12-06
    • 2018-11-15
    • 2013-03-25
    相关资源
    最近更新 更多