【问题标题】:Selecting parent style based on condition in SCSS根据 SCSS 中的条件选择父样式
【发布时间】:2021-11-08 01:11:51
【问题描述】:

我有一个表格,我使用display: flex 来显示表格。我还有两种类型的行,一种是标题,另一种是表格的主体。表格的标题文本居中对齐。但我希望正文的其中一列右对齐。

现在您注意到我用相同的宽度定义了净价列的标题和正文,以便它们可以适当地添加相同的宽度。现在我想添加一个样式,我只需要设置应该右对齐的 bodynet price 列。

如何在net-price SCSS 块内添加选择器,使样式仅适用于表体而不适用于表头?

<table>
        <thead class="service-grid__wrapper__header">
            <td>Header one</td><td class="net-price">Header two</td>
        </thead>
        <tbody class="service-grid__wrapper__body">
            <td>Column one</td><td class="net-price">Columntwo</td>
        </tbody>
    </table>

    .service-grid {
          &__wrapper {
            margin: 0;
            background-color: $white;
            &__header {
              font-family: "Roboto-Medium";
              display: flex;
            }
            &__body {
              display: flex;
              font-family: "Roboto-Regular";
            }
            .net-price {
              width: 160px;
              .myaddtional-style { /* Style block where I need to apply only to the body cell and not the header cell */
                text-align: right;
              }
            }
          }
        }

【问题讨论】:

  • 我认为您确实应该尝试减少您发布的样式代码,以使问题尽可能清晰。我很难理解你在做什么。哦,最好在markdown中将html和样式分成两个代码块。
  • @Martin 道歉,为了更清楚,这个问题已经被淡化了。

标签: html css sass styles


【解决方案1】:

您需要在选择器中使用service-grid__wrapper__body 类。 在当前 SCSS 中表达这一点的最简单方法如下所示(省略所有其他 css 属性):

.service-grid {
  &__wrapper {

    // order is important, regular styles before specialized styles
    .net-price {
      width: 160px; // the regular styles for net-price
    }

    &__header {
    }

    &__body {
      .net-price { text-align: right; } // the special handling inside the __body
    }

  }
}

或者

.service-grid {
  &__wrapper {

    &__header {
    }

    &__body {
    }

    .net-price {
      width: 160px;
    }

    &__body .net-price {
      text-align: right;
    }

  }
}

这是另一种让所有同事感到困惑的方法:

.service-grid {
  &__wrapper {

    &__header {
    }

    &__body {
    }

    $wrapper-class: &;

    .net-price {
      width: 160px;
      @at-root #{$wrapper-class}__body .net-price { text-align: right; }
    }

  }
}

【讨论】:

  • 这正是我想要避免的。这可以在没有额外的“净价格块”的情况下实现吗?
  • @Kirk 好吧,它并没有变得更具可读性,但我添加了第三种选择。
猜你喜欢
  • 2021-12-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-12
  • 1970-01-01
相关资源
最近更新 更多