【问题标题】:How to apply a style to both parent and child in SCSS如何在 SCSS 中将样式应用于父级和子级
【发布时间】:2017-02-22 22:19:57
【问题描述】:

我有这种情况:

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

我想给两个宽度:100% 规则。 SCSS有没有比写更好的方法:

.parent{
    width: 100%;
    .child{
        width: 100%;
    }
 }

我对 SCSS 语法比较陌生,所以也许这是一个非常简单的问题,但我找不到简单的答案。

【问题讨论】:

    标签: css sass


    【解决方案1】:

    你用&amp;定位当前选择器,所以你可以这样写:

    .parent {
      &, .child {
        width: 100%;
      }
    }
    

    作为奖励,您还可以使用&amp;,如下所示:

    .parent {
      &.mother {
        // target elements classed `parent` AND `mother`
    
        .grandparent & {
          // target elements classed `parent` AND `mother` with a 
          // `grandparent` ancestor.
        }
      }
    }
    

    【讨论】:

    • 这意味着如果我添加逗号 (,),& 运算符也会将该属性添加到目标元素,而不是像我删除逗号那样添加到 .parent (plus) .child班级。我对吗?想要我的意思是:如果我写了|| .parent { &.child { ... } } ||规则应该被添加到
      元素中......
    • 重要的是空间。 &amp; .child(注意空格)将在当前选择下定位.child&amp;.child 将增加当前选择的特异性具有.child 类。我的答案中的逗号是因为它的目标是 both .parent.parent .child
    【解决方案2】:

    尽量不要在子元素上设置width :)

    【讨论】:

      猜你喜欢
      相关资源
      最近更新 更多
      热门标签