Ted
Ted

Reputation: 14927

How do I target a first-child that is visible (after children that are set to display:none), with only CSS

I need to target the first <td> element in a table row that is visible--meaning it does not have inline styling of display:none.

Here's the gotchyas:

Here is a quick sample of what the code looks like:

<table>
    <thead>
        <tr>
            <th style="display:none">Header1</th>
            <th>Header2</th>
            <th>Header3</th>
            <th>Header4</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td style="display:none">Body1</td>
            <td>Body2</td>
            <td>Body3</td>
            <td>Body4</td>
        </tr>
    </tbody>
</table>

I tried messing with something like this to no avail:

table > tbody > tr > td:first-of-type:not([style*="display:none"]) 

Here's a fiddle to mess with

Thanks in advance.

Upvotes: 5

Views: 3074

Answers (2)

Teepeemm
Teepeemm

Reputation: 4508

This will style anything that isn't "display:none", but undo that when it gets to a subsequent one that isn't "display:none".

table > tbody > tr > td:not([style*="display:none"]) {
    color: red;
}
table > tbody > tr > td:not([style*="display:none"]) ~ td:not([style*="display:none"]) {
    color: inherit;
}
<table>
  <thead>
    <tr>
      <th style="display:none">Header1</th>
      <th>Header2</th>
      <th>Header3</th>
      <th>Header4</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td style="display:none">Body1</td>
      <td>Body2</td>
      <td>Body3</td>
      <td>Body4</td>
    </tr>
    <tr>
      <td>First</td>
      <td>Second</td>
      <td>Third</td>
    </tr>
  </tbody>
</table>

Upvotes: 2

Oka
Oka

Reputation: 26355

If your hidden elements are always at the beginning of the row, you can use the direct sibling selector for this +.

td:first-child,
td[style*="none"] + td {
  color: red;
}
<table>
  <thead>
    <tr>
      <th style="display:none">Header1</th>
      <th>Header2</th>
      <th>Header3</th>
      <th>Header4</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td style="display:none">Body1</td>
      <td>Body2</td>
      <td>Body3</td>
      <td>Body4</td>
    </tr>
    <tr>
      <td>First</td>
      <td>Second</td>
      <td>Third</td>
    </tr>
    <tr>
      <td style="display:none">and</td>
      <td>here's</td>
      <td>an</td>
      <td style="display:none">edge</td>
      <td>case</td>
    </tr>

  </tbody>
</table>

Upvotes: 7

Related Questions