only-of-class with pure CSS?

2019-09-03 06:43发布

问题:

I need to hide .meta elements only if there are not other .meta elements in the list.
Basically I need the same behavior of :only-of-type but for classes.

So, if I have:

<table>
    <tr class="meta"><td>lorem</td></tr>
    <tr class="row"><td>row</td></tr>
</table>

.meta will be hidden

If I have:

<table>
    <tr class="meta"><td>lorem</td></tr>
    <tr class="row"><td>row</td></tr>
    <tr class="meta"><td>lorem</td></tr>
</table>

.meta will be shown.

The CSS should looks like:

.meta:only-of-class { display: none; }

Is it possible with pure CSS?

Edit:

I've even tried with this markup (not much W3C compilant but who care):

<table>
    <tr><th class="meta"><lorem</th><tr>
    <tr class="row"><td>row</td></tr>
</table>

With this CSS:

th:only-of-type { display: none; }

But it doesn't work (and here I've not really idea of why it doesn't)

回答1:

A possibile workaround could be contrived by using a dummy item in those lists which contain more than one .meta element:

<ul>
    <li class="meta">lorem</li>
    <li class="row">row</li>
</ul>

<ul>
    <li class="meta">dummy</li>
    <li class="meta">lorem</li>
    <li class="row">row</li>
    <li class="meta">lorem</li>
</ul>

Then you would give to every item the display: none property, and override it only when you have more than one .meta sibling:

ul > .meta {
    display: none;
}

ul > .meta ~ .meta {
    display: list-item;
}