【问题标题】:Sass with BEM, inherit selectorSass 与 BEM,继承选择器
【发布时间】:2014-12-05 20:49:09
【问题描述】:

我使用的是 Sass 3.4.1 和 BEM,所以我的 scss 是:

.photo-of-the-day{
    &--title{
        font-size: 16px;
    }
}

我希望每次将鼠标悬停在 .photo-of-the-day 上时,标题都会发生一些事情,这很常见,所以通常在 css 中:

.photo-of-the-day:hover .photo-of-the-day--title{
    font-size:12px
}

问题是使用 BEM,这是我发现的唯一方法,看起来有点丑

.photo-of-the-day{
    &--title{
        font-size: 16px;
    }
    &:hover{
        background: red;
        /* this is ugly */
        .photo-of-the-day--title{
            text-decoration: underline;
        }
    }
}

所以我想知道是否可以继承 .photo-of-the-day 选择器并在悬停时使用它以避免再次复制完整的选择器。

理想情况下是这样的:

.photo-of-the-day{
    &--title{
        font-size: 16px;
    }
    &:hover{
        background: red;
        &&--title{
            text-decoration: underline;
        }
    }
}

或者接近回归到 BEM 的父选择器的东西。有可能吗?

【问题讨论】:

标签: css sass bem


【解决方案1】:

如果你坚持嵌套一切,你能做的最好的就是:

.photo-of-the-day {
    $root: &;
    &--title{
        font-size: 16px;
    }
    &:hover{
        #{$root}--title {
            text-decoration: underline;
        }
    }
}

【讨论】:

    【解决方案2】:

    您可以使用以下语法:

    .photo-of-the-day {
        &--title {
            font-size: 16px;
        }
        &:hover &--title {
            text-decoration: underline;
        }
    }
    

    【讨论】:

    • 这个问题是如果我做那个解决方案我失去了悬停范围所以不能这样做:&:hover{ cursor: pointer; background: red; ... .photo-of-the-day--title{ text-decoration: underline; } }
    • @alexrqs 还有?没有规则说你必须嵌套所有东西。有嵌套的解决方案实际上更冗长。
    • @alexrqs 您必须独立于&:hover &--title 使用&:hover { /* ... */ }
    • @alexrqs - 你是绝对正确的。虽然这可行,但这意味着重复 :hover 选择器需要多少次,失去 SASS 给你的任何 DRY 方面。很伤心。
    猜你喜欢
    • 2023-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-29
    • 1970-01-01
    • 2023-04-11
    • 2016-02-25
    相关资源
    最近更新 更多