Search code examples
csssassdayofweek

Sass / CSS programmatically set rule based on parent class number


For a set of open times I want to style the current day to make it stand out. In React I'm setting using new Date().getDay() to get the day number (1-7) and setting this on the parent like so:

<ul className={"opentimes day-" + new Date().getDay()}>

This results in the following output for Wednesday for example:

<ul class="opentimes day-3">

In the Sass/CSS I'm setting the rule based on the nth-child. The day-1 part doesn't really serve any computational purpose.

.opentimes {
    &.day-1 { li:nth-child(1) { font-weight: 600;}}
    &.day-2 { li:nth-child(2) { font-weight: 600;}}
    &.day-3 { li:nth-child(3) { font-weight: 600;}}
    &.day-4 { li:nth-child(4) { font-weight: 600;}}
    &.day-5 { li:nth-child(5) { font-weight: 600;}}
    &.day-6 { li:nth-child(6) { font-weight: 600;}}
    &.day-7 { li:nth-child(7) { font-weight: 600;}}
}

Is there a way to be a bit smarter with this and use the class on the opentimes level to indicate which child element to style (either in vanilla CSS or Sass)?

I thought something like this might be possible but not sure if it actually is:

&.day-1 .flex-half:nth-child(1),
&.day-2 .flex-half:nth-child(2),
&.day-3 .flex-half:nth-child(3),
&.day-4 .flex-half:nth-child(4),
&.day-5 .flex-half:nth-child(5),
&.day-6 .flex-half:nth-child(6),
&.day-7 .flex-half:nth-child(7) {
    font-weight: 600;
}

Solution

  • You can use a for loop and replace the number with the variable.

    .opentimes {
        @for $i from 1 through 7 {
            &.day-#{$i} { li:nth-child(#{$i}) { font-weight: 600; } }
        }
    }
    

    Which results in

    .opentimes.day-1 li:nth-child(1) {
      font-weight: 600;
    }
    .opentimes.day-2 li:nth-child(2) {
      font-weight: 600;
    }
    .opentimes.day-3 li:nth-child(3) {
      font-weight: 600;
    }
    .opentimes.day-4 li:nth-child(4) {
      font-weight: 600;
    }
    .opentimes.day-5 li:nth-child(5) {
      font-weight: 600;
    }
    .opentimes.day-6 li:nth-child(6) {
      font-weight: 600;
    }
    .opentimes.day-7 li:nth-child(7) {
      font-weight: 600;
    }