Home  >  Article  >  Web Front-end  >  Why Can\'t You Group Descendants in CSS Selectors?

Why Can\'t You Group Descendants in CSS Selectors?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-02 14:32:02614browse

Why Can't You Group Descendants in CSS Selectors?

Why Can't You Group Descendants in a CSS Selector?

Traditionally, CSS has lacked an efficient method for applying the same style to a group of descendants. Consider the following HTML table:

<code class="html"><table id='myTable'>
  <tr>
    <th></th>
    <th></th>
    <th></th>
  </tr>
  .
  .
  .
  <tr>
    <td></td>
    <td></td>
    <td></td>
  </tr>
</table></code>

To style both column headings and cells, the traditional selector requires specifying both elements:

<code class="css">#myTable th, #myTable td {}</code>

Why isn't there a more concise syntax like:

<code class="css">#myTable (th,td) {}</code>

Evolution of a Solution

Initially, there was no proposal for a useful syntax until 2008, when the :any() pseudo-class was proposed. Mozilla implemented it as :-moz-any() in 2010, followed by WebKit's :-webkit-any() in 2011.

However, using both prefixes simultaneously necessitated duplicating rulesets, defeating the purpose. As a result, these prefixed selectors are now considered impractical.

The Selectors level 4 working draft now contains a proposal for :matches(), based on the original :any() but with potential enhancements. However, browser support is expected to take some time.

Workarounds

For styling both th and td elements specifically, you can use * instead, assuming that the tr elements contain only cell elements:

<code class="css">#myTable tr > * {}</code>

Alternatively, for performance reasons, you may prefer the longer traditional method.

The above is the detailed content of Why Can\'t You Group Descendants in CSS Selectors?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn