【问题标题】:Use parents' property as variable with SASS使用父母的财产作为 SASS 的变量
【发布时间】:2013-09-28 10:04:52
【问题描述】:

是否可以将父级的属性用作变量? 例如,在这段代码中,我希望能够为“inner-box”元素赋予与其父“box”相同的颜色。

使其类似于 .inner-box {background-color: $Outer-Parent's-Color;}

Example on Fiddle

<div class="box">
    <div class="box1">
        <div class = "inner-box">
            BOX
        </div>
    </div>
</div>

<div class="box red">
    <div class="box1">
        <div class = "inner-box">
            RED BOX
        </div>
    </div>
</div>

和css

.box {
    width: 100px;
    padding: 10px;
    margin: 10px;
    background-color: blue;
}
.box1 {
    background-color: darkblue;
    padding: 10px;
}
.box.red {
    background-color: red;
}
.box.red .box1 {
    background-color: darkred;
}
.inner-box {
    background-color: $Outer-Parent's-Color;
}

【问题讨论】:

标签: css sass


【解决方案1】:

如果你使用的是 SASS,你可以在盒子中嵌入内盒

.box {    
    width: 100px;
    padding: 10px;
    margin: 10px;
    background-color: blue;

    &.inner-box {
        background-color: inherit;
    }
}

【讨论】:

    【解决方案2】:

    只需使用继承值:

    .inner-box {
            background-color: inherit;
        }
    

    【讨论】:

      【解决方案3】:

      @Thomas Wood 和@Oliver Benns:继承不与父母一起工作吗?在我看来,我们与祖父母和孩子打交道。所以没有什么花哨的,只是简单的 css 添加一个选择器:

      .box {
          width: 100px;
          padding: 10px;
          margin: 10px;
      }
      .box, .box div div /* Selects the grandparent and child and is not a fancy sass nested selector */
          background-color: blue;
      }
      

      或者用 sass @mixin 和 @for 来计算颜色值:

      @mixin grandparent($h, $width: 200px) {
        width: $width;
        background-color: hsl(20 * $h, 100%, 50%);
      }
      
      @mixin child($h) {
        background-color: hsl(20 * $h, 100%, 50%);
      }
      
      @for $i from 1 through 6 {
        .box-#{$i} { @include grandparent($i, 20 * $i); }
        .box-#{$i} div div { @include child($i); }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-06-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-02-01
        相关资源
        最近更新 更多