如何使用嵌套类选择器来选择tr和td?

huangapple go评论110阅读模式
英文:

How to use nested class selector for tr and td?

问题

如果这是我的HTML结构:

<tr class="editing">
   <td class="col-2"></td>
   <td class="col-2"></td>
</tr>

为什么这个嵌套的CSS能正常工作:

.editing {
    padding: 1em 1.5em;      
    .col-2 {
        font-size: 11em;
    }
}

但这个不行:

.editing {
    padding: 1em 1.5em;      
    td {
        font-size: 11em;
    }
}

我正在使用Chrome 114,根据https://caniuse.com/css-nesting,CSS嵌套是被支持的。我知道如何使用非嵌套的方法,但这是一个使用新支持的CSS特性的练习。

英文:

If this is my html structure:

&lt;tr class=&quot;editing&quot;&gt;
   &lt;td class=&quot;col-2&quot;&gt;&lt;/td&gt;
   &lt;td class=&quot;col-2&quot;&gt;&lt;/td&gt;
&lt;/tr&gt;

how come this nested css works fine:

.editing {
    padding: 1em 1.5em;      
    .col-2 {
        font-size: 11em;
    }
}

but this does not:

.editing {
    padding: 1em 1.5em;      
    td {
        font-size: 11em;
    }
}

I am using Chrome 114 and according to https://caniuse.com/css-nesting CSS nesting is supported. I know how to use a non-nested approach this is an exercise in using a newly supported CSS feature.

答案1

得分: 2

根据这篇文章的说法:

> HTML元素目前需要在前面添加&amp;符号或用:is()包装。

...以及规范的内容:

> 嵌套样式规则的选择器不得以标识符或函数表示法开头。

这意味着您需要将您的第二个规则重写为:

.editing {
  padding: 1em 1.5em;

  :is(td) {
    font-size: 11em;
  }
}

...或者:

.editing {
  padding: 1em 1.5em;

  &amp; td {
    font-size: 11em;
  }
}
英文:

According to this article:

> HTML elements currently require the &amp; symbol in front or being wrapped with :is().

...and the spec:

> The selector of nested style rules must not start with an identifier or a functional notation.

This means you need to rewrite your second rule as:

.editing {
  padding: 1em 1.5em;

  :is(td) {
    font-size: 11em;
  }
}

...or:

.editing {
  padding: 1em 1.5em;

  &amp; td {
    font-size: 11em;
  }
}

答案2

得分: -1

嵌套的CSS选择器在所有浏览器中目前尚不受支持。现在不推荐这样做。

您应该像这样不嵌套地使用它们:

.editing {
  padding: 1em 1.5em;
}

.editing .col-2 {
  font-size: 11em;
}
/* 或者 */
.editing td {
  font-size: 11em;
}
英文:

nested CSS selectors are not supported (yet) in all browsers. It's not really recommended to do that right now.

You should just use them un-nested like this:

.editing {
  padding: 1em 1.5em;
}

.editing .col-2 {
  font-size: 11em;
}
/* or */
.editing td {
  font-size: 11em;
}

huangapple
  • 本文由 发表于 2023年6月12日 10:23:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/76453311.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定