首页 > 解决方案 > 我如何使用 Sass 的“&”(与号)来检查元素是否是某个标签(例如:div)

问题描述

我正在使用 Sass 对表格进行样式设置,并且我想根据该元素的标签(<td /><th />)以不同的方式自定义具有某个类的元素的样式。

我想过使用

.foo {
  /* td styles here */
  & th { /* th styles here */ }
}

但这不起作用。(它选择具有 th 标签的“.foo”的孩子)

有什么方法可以使用 Sass 的“&”(与号)根据标签对具有相同类的元素进行样式设置?

标签: htmlcsssass

解决方案


利用:is()

.foo {
   &:is(td) { /* td styles here */ }
   &:is(th) { /* th styles here */ }
}

编译后的 SCSS 将产生这个 CSS

.foo:is(td) {
  color: #9bc
}

.foo:is(th) {
  color: #666
}
<table>
  <tr>
    <th class="foo">heading</th>
    <td class="foo">table cell</td>
  </tr>
</table>


推荐阅读