Sass / CSS 根据父类编号以编程方式设置规则

问题描述 投票:0回答:1

对于一组开放时间,我想设计当天的样式以使其脱颖而出。在 React 中,我设置使用 new Date().getDay() 来获取天数 (1-7) 并将其设置在父级上,如下所示:

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

这会导致周三的以下输出:

<ul class="opentimes day-3">

在 Sass/CSS 中,我根据第 n 个子节点设置规则。

day-1
部分实际上并没有任何计算目的。

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

有没有一种方法可以更聪明一点,并在 opentimes 级别使用类来指示要设置哪个子元素的样式(在普通 CSS 或 Sass 中)?

我认为这样的事情可能是可能的,但不确定它是否真的是:

&.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;
}
css sass dayofweek
1个回答
0
投票

您可以使用 for 循环并将数字替换为变量。

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

这会导致

.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;
}
© www.soinside.com 2019 - 2024. All rights reserved.