-1

给定:一组简单的彩色高光,仅在 CSS 中控制。

有什么办法可以缩短下面一大块 CSS 代码,同时保持相同的结果?

换句话说,有没有办法在选择多个声明时仅使用 CSS 来消除代码中的重复性?nth-of-type

//CSS
nav:hover mark:nth-of-type(01){background:linear-gradient(to left, transparent, rgb(192 0 192 / 1))}
nav:hover mark:nth-of-type(02){background:linear-gradient(to left, transparent, rgb(180 0 250 / 1))}
nav:hover mark:nth-of-type(03){background:linear-gradient(to left, transparent, rgb(220 0 250 / 1))}
nav:hover mark:nth-of-type(04){background:linear-gradient(to left, transparent, rgb(220 0 120 / 1))}
nav:hover mark:nth-of-type(05){background:linear-gradient(to left, transparent, rgb(210 0 130 / 1))}
nav:hover mark:nth-of-type(06){background:linear-gradient(to left, transparent, rgb(202 184 0 / 1))}
nav:hover mark:nth-of-type(07){background:linear-gradient(to left, transparent, rgb(230 196 0 / 1))}
nav:hover mark:nth-of-type(08){background:linear-gradient(to left, transparent, rgb(145 190 0 / 1))}
nav:hover mark:nth-of-type(09){background:linear-gradient(to left, transparent, rgb(135 182 0 / 1))}
nav:hover mark:nth-of-type(10){background:linear-gradient(to left, transparent, rgb(0 204 227 / 1))}
nav:hover mark:nth-of-type(11){background:linear-gradient(to left, transparent, rgb(0 187 253 / 1))}
nav:hover mark:nth-of-type(12){background:linear-gradient(to left, transparent, rgb(0 192 212 / 1))}
nav:hover mark:nth-of-type(13){background:linear-gradient(to left, transparent, rgb(0 167 255 / 1))}
nav:hover mark:nth-of-type(14){background:linear-gradient(to left, transparent, rgb(0 165 150 / 1))}
nav:hover mark:nth-of-type(15){background:linear-gradient(to left, transparent, rgb(12 156 23 / 1))}
nav:hover mark:nth-of-type(16){background:linear-gradient(to left, transparent, rgb(16 20 162 / 1))}
```
4

1 回答 1

2

对于纯 CSS,您仍然需要大量重复,但这更易读,使用 CSS 变量:

nav mark:nth-of-type(01){--c: rgb(192 0 192 / 1)}
nav mark:nth-of-type(02){--c: rgb(180 0 250 / 1)}
nav mark:nth-of-type(03){--c: rgb(220 0 250 / 1)}
nav mark:nth-of-type(04){--c: rgb(220 0 120 / 1)}
nav mark:nth-of-type(05){--c: rgb(210 0 130 / 1)}
nav mark:nth-of-type(06){--c: rgb(202 184 0 / 1)}
nav mark:nth-of-type(07){--c: rgb(230 196 0 / 1)}
nav mark:nth-of-type(08){--c: rgb(145 190 0 / 1)}
nav mark:nth-of-type(09){--c: rgb(135 182 0 / 1)}
nav mark:nth-of-type(10){--c: rgb(0 204 227 / 1)}
nav mark:nth-of-type(11){--c: rgb(0 187 253 / 1)}
nav mark:nth-of-type(12){--c: rgb(0 192 212 / 1)}
nav mark:nth-of-type(13){--c: rgb(0 167 255 / 1)}
nav mark:nth-of-type(14){--c: rgb(0 165 150 / 1)}
nav mark:nth-of-type(15){--c: rgb(12 156 23 / 1)}
nav mark:nth-of-type(16){--c: rgb(16 20 162 / 1)}

nav:hover mark:nth-of-type(n){background:linear-gradient(to left, transparent, var(--c))}
于 2021-03-27T15:24:16.330 回答