CSS Selector for nth range?
如何调整下面的 CSS 选择器:
1
2 3 |
.myTableRow td:nth-child(?){
background-color: #FFFFCC; } |
所以它适用于
1
2 3 4 5 6 7 8 9 |
<table>
<tr class="myTableRow"> <td>column 1</td> <td>column 2</td> <td>column 3</td> <td>column 4</td> <td>column 5</td> </tr> </table> |
您可以使用的另一种方法是:
1
2 3 |
.myTableRow td:nth-child(n+2):nth-child(-n+4){
background-color: #FFFFCC; } |
这更清楚一点,因为它包含了范围内的数字(
它也更健壮一些,因为您不必考虑项目的总数。
澄清:
1
2 |
:nth-child(n+X) /* all children from the Xth position onward */
:nth-child(-n+x) /* all children up to the Xth position */ |
示例:
1
2 3 4 5 6 7 8 9 10 11 |
#nn div { width: 40px; height: 40px; background-color: black; display: inline-block; margin-right: 10px; } #nn div:nth-child(n+3):nth-child(-n+6) { |
1 |
你不能用一个
1
2 3 |
.myTableRow td:nth-child(n+2):nth-last-child(n+2){
background-color: #FFFFCC; } |
或者,不使用公式,只需排除
1
2 3 |
.myTableRow td:not(:first-child):not(:last-child){
background-color: #FFFFCC; } |
如果你想选择元素 2 到 4,你可以这样做:
1
2 3 |
td:nth-child(-n+4):nth-child(n+2) {
background: #FFFFCC; } |
提醒选择器链的顺序应该是从大到小。 Safari 存在一个错误,导致该技术无法正常工作。
我创建了一个非常简单的代码,以便直观地清楚如何从同一页面上的其他用户的响应中选择列或行。
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 |
<!doctype html>
<html lang="pt-br"> <head> <!— https://stackoverflow.com/questions/15639247/css-selector-for-nth-range —> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1, user-scalable=yes, shrink-to-fit=no"> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet"> <style> table{margin: 50px auto;} thead tr{background-color: gray; font-weight: 700;} td{border: 1px solid black;padding: 2px 8px;} table tr:nth-child(n+2):nth-child(-n+3){background-color:blue;} table td:nth-child(n+2):nth-child(-n+3){background-color:red;} </style> </head> <body> <table> <thead> <tr> <td>AAA</td> <td>BBB</td> <td>CCC</td> <td>DDD</td> <td>EEE</td> <td>FFF</td> </tr> </thead> <tbody> <tr> <td>111</td> <td>111</td> <td>111</td> <td>111</td> <td>111</td> <td>111</td> </tr> <tr> <td>222</td> <td>222</td> <td>222</td> <td>222</td> <td>222</td> <td>222</td> </tr> <tr> <td>333</td> <td>333</td> <td>333</td> <td>333</td> <td>333</td> <td>333</td> </tr> <tr> <td>444</td> <td>444</td> <td>444</td> <td>444</td> <td>444</td> <td>444</td> </tr> <tr> <td>555</td> <td>555</td> <td>555</td> <td>555</td> <td>555</td> <td>555</td> </tr> </tbody> </table> </body> </html> |
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/269244.html
赞 (0)