Kirk
Kirk

Reputation: 5077

Selecting parent style based on condition in SCSS

I have a table where I used display: flex to display the table. I also have two types of rows where one is a header, and another one is a body of the table. The table's header text is center aligned. But I want one of the columns of the body to be right-aligned.

Now you notice that I defined the header and body of net price columns with the same width so that they can appropriately add the same width. Now I want to add a style where I need to set only the net price column of a body that should be right-aligned.

How can I add a selector within the net-price SCSS block so that the style is only applicable to the body and not the header of the table?

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

Upvotes: 0

Views: 497

Answers (1)

Martin
Martin

Reputation: 6156

You would need to use the service-grid__wrapper__body class in your selector. The simplest way to express this in your current SCSS would look like this (all other css properties omitted):

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

  }
}

alternatively

.service-grid {
  &__wrapper {

    &__header {
    }

    &__body {
    }

    .net-price {
      width: 160px;
    }

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

  }
}

And here is another alternative to confuse all your colleagues:

.service-grid {
  &__wrapper {

    &__header {
    }

    &__body {
    }

    $wrapper-class: &;

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

  }
}

Upvotes: 1

Related Questions