André Reichelt
André Reichelt

Reputation: 1631

Apply css background to text content of a table cell only

I have an HTML table. For specific rows (which have a highlighting class), I want to apply a background, which makes the text hard to read. A solution would be, to put a semi-transparent, white background behind the text only. The easiest solution would be, to put every text element in a separate span, but unfortunately I cannot modify the HTML structure in this specific case.

So, is there a way to apply a CSS rule only to the text contained in a table cell (td) with pure CSS?

Upvotes: 2

Views: 2246

Answers (1)

Hao Wu
Hao Wu

Reputation: 20699

You can use background-clip: content-box to apply the background only for the content.

td {
  padding: 10px;
}

.bg-normal {
  background-color: lime;
}

.bg-text {
  background-color: pink;
  
  /* apply background only for text*/
  -webkit-background-clip: content-box;
  background-clip: content-box;
}
<table>
  <thead>
    <tr>
      <th>Head 1</th>
      <th>Head 2</th>
      <th>Head 3</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Content 1</td>
      <td>Content 2</td>
      <td>Content 3</td>
    </tr>
    <tr class="bg-normal">
      <td>Content 1</td>
      <td>Content 2</td>
      <td>Content 3</td>
    </tr>
    <tr class="bg-text">
      <td>Content 1</td>
      <td>Content 2</td>
      <td>Content 3</td>
    </tr>
  </tbody>
</table>

Upvotes: 1

Related Questions