Jeff G
Jeff G

Reputation: 4677

Add CSS Class to Sphinx Table Cell

Is there a way to add a CSS class to a Sphinx-generated HTML table? For example, I want to modify the following RST table definition:

+-------+
| cell1 |
+-------+
| cell2 |
+-------+

To generate the following HTML (roughly):

<table>
    ...
    <tbody>
        <tr><td>cell1</td></tr>
        <tr><td class="someClass">cell2</td></tr>
    </tbody>
</table>

The following RST adds the specified class to a new paragraph element within the cell (instead of on the cell itself):

+--------------------------+
| cell1                    |
+--------------------------+
| .. rst-class:: someClass |
| cell2                    |
+--------------------------+

Is there any way to modify the original RST source to generate the specified HTML table?

Upvotes: 5

Views: 711

Answers (2)

Jeff G
Jeff G

Reputation: 4677

As of December 2023, all major desktop and mobile browsers support the CSS has selector. This enables applying the style to the paragraph element, then writing CSS such as:

td:has(>.someClass) {
    /* Some style to apply to the td here */
}

Upvotes: 1

G. Milde
G. Milde

Reputation: 929

No, unfortunately there is no way to do this in standard rST.

The "class" directive ("rst-class" in Sphinx) sets the classes attribute value on its content or on the first immediately following non-comment document-tree element. As table cells are nested in table row elements, there is no way to pass a class argument value to cells in the first column.

As a workaround, you may use

+--------------------------+
| cell1                    |
|                          |
| .. rst-class:: someClass |
+--------------------------+
| cell2                    |
+--------------------------+

to get "someclass" on the second table row element and use the tr.someclass:first-child: selector for CSS styling.

Note that class values are normalized.

Upvotes: 2

Related Questions