如何在Vanilla Extract中选中并设置tbody首个单元格样式?
在Vanilla Extract中选中
tbody tr:first-child td:first-child元素的方法 问题描述
我正尝试在Vanilla Extract中为<tbody>设置圆角样式,但不知道如何选中特定子元素,请问如何选中tbody tr:first-child td:first-child元素?
原生CSS参考实现
table { border-collapse: separate; } tbody td { border-width: 5px; border-color: red; border-style: solid; } tbody tr:first-child td:first-child { border-color: black; color: white; background-color: red; border-radius: 1rem 0 0 0; }
对应HTML结构
<table> <thead> <tr> <td>Wong</td> <td>Loo</td> <td>See</td> </tr> </thead> <tbody> <tr> <td>One</td> <td>Two</td> <td>Three</td> </tr> <tr> <td>Son</td> <td>Woo</td> <td>Bee</td> </tr> <tr> <td>Tom</td> <td>Soon</td> <td>Tree</td> </tr> </tbody> <tfoot> <tr> <td>Total</td> <td colspan="2">$1 million</td> </tr> </tfoot> </table>
Vanilla Extract实现方案
在Vanilla Extract中,你可以通过嵌套选择器的方式,完全对应原生CSS的层级关系,代码如下:
import { createStyles } from '@vanilla-extract/css'; export const tableStyles = createStyles({ table: { borderCollapse: 'separate' }, tbody: { // 对应原生CSS的tbody td '& td': { borderWidth: '5px', borderColor: 'red', borderStyle: 'solid' }, // 对应原生CSS的tbody tr:first-child td:first-child '& tr:first-child td:first-child': { borderColor: 'black', color: 'white', backgroundColor: 'red', borderRadius: '1rem 0 0 0' } } });
然后在HTML中为元素添加对应的类名:
<table class="${tableStyles.table}"> <thead> <tr> <td>Wong</td> <td>Loo</td> <td>See</td> </tr> </thead> <tbody class="${tableStyles.tbody}"> <tr> <td>One</td> <td>Two</td> <td>Three</td> </tr> <tr> <td>Son</td> <td>Woo</td> <td>Bee</td> </tr> <tr> <td>Tom</td> <td>Soon</td> <td>Tree</td> </tr> </tbody> <tfoot> <tr> <td>Total</td> <td colspan="2">$1 million</td> </tr> </tfoot> </table>
说明
&符号在Vanilla Extract的嵌套选择器中代表当前父元素(这里就是.tbody类对应的<tbody>元素)- 通过
& tr:first-child td:first-child的写法,完全复刻原生CSS的选择器逻辑,实现目标元素的样式设置
内容的提问来源于stack exchange,提问作者ViktorMS
相关产品推荐
相关产品推荐

