如何利用Tailwind CSS的:group-first-of-type选择器定位表格中深层嵌套的首个<tr>元素
如何利用Tailwind CSS的:group-first-of-type选择器定位表格中深层嵌套的首个元素
首先得说清楚为什么你原来的写法没达到预期——group-first-of-type这个选择器的逻辑是:当前元素是它的直接父元素里的第一个同类型子元素时生效。而你的<tr>分别嵌套在<thead>和<tbody>里,这两个是不同的父元素,所以<thead>里的<tr>是<thead>的第一个同类型子元素,<tbody>里的第一个<tr>也是<tbody>的第一个同类型子元素,最终两个<tr>的第一个<td>都会被加上圆角,这显然不是你想要的。
你要的是整个<table>范围内的第一个<tr>,不管它在<thead>还是<tbody>里,那我们得换个思路,不用group-first-of-type,而是直接基于<table>的后代选择器来精准定位:
方案一:纯Tailwind任意选择器实现(无需额外CSS)
直接在<table>上添加两个任意选择器类,分别覆盖「有<thead>」和「无<thead>」的场景:
<table class="[&>thead:first-child>tr:first-of-type>td:first-of-type]:rounded-tl-md [&>tbody:first-child>tr:first-of-type>td:first-of-type]:rounded-tl-md"> <!-- 这个thead可能存在或不存在 --> <thead> <tr> <td>My Cell</td> <td>My Other Cell</td> </tr> </thead> <tbody> <tr> <td>My Cell</td> <td>My Other Cell</td> </tr> <tr> <td>My Cell</td> <td>My Other Cell</td> </tr> </tbody> </table>
- 第一个类
[&>thead:first-child>tr:first-of-type>td:first-of-type]:rounded-tl-md:当表格第一个子元素是<thead>时,选中<thead>里第一个<tr>的第一个<td>加圆角。 - 第二个类
[&>tbody:first-child>tr:first-of-type>td:first-of-type]:rounded-tl-md:当表格第一个子元素是<tbody>(也就是没有<thead>)时,选中<tbody>里第一个<tr>的第一个<td>加圆角。
这样不管有没有<thead>,只有整个表格里的第一个<tr>的第一个<td>会被加上左上角圆角,完全符合你的需求。
方案二:自定义Tailwind工具类(更整洁)
如果觉得table上的类太长,你可以用Tailwind的@layer自定义一个工具类,在你的CSS文件里添加:
@layer utilities { .table-first-tr-rounded-tl { & > thead:first-child > tr:first-of-type > td:first-of-type, & > tbody:first-child > tr:first-of-type > td:first-of-type { border-top-left-radius: 0.375rem; /* 对应Tailwind的rounded-tl-md */ } } }
然后给table加这个类就行:
<table class="table-first-tr-rounded-tl"> <!-- 剩余结构不变 --> </table>
为什么不推荐用group-first-of-type?
因为它的设计逻辑就是绑定直接父元素的第一个同类型子元素,而<tr>的父元素是<thead>或<tbody>,这两个是平行的容器,没法通过group关联到整个<table>的层级。所以针对这种跨容器找第一个元素的场景,直接用后代选择器反而更直接可靠。
备注:内容来源于stack exchange,提问作者Adam Young
相关产品推荐
相关产品推荐

