Search code examples
python-sphinxrestructuredtext

Setting Column Width with restructuredText Grid Tables


I have the following grid table in rST. I'd like to control the column widths for HTML output so that Field type occupies 20% of the table's width, Description occupies 30%, and Example occupies 50%.

+-------------+-----------------+-----------------------+
|Field type   |Description      |Example                |
+-------------+-----------------+-----------------------+

The ..tablularcolumns directive has no impact, neither does the combination ..table and :width:. For example, the following has no impact.

.. tabularcolumns:: |p{2cm}|p{3cm}|p{5cm}|

The answer at the following SO link does not work.

How to fix column width in reStructuredText tables?

Any recommendation will be thoroughly blessed.


Solution

  • Two options.

    Use the widths option for tables.

    .. table:: This is my table
        :widths: 20 30 50
    
        +-------------+-----------------+-----------------------+
        |Field type   |Description      |Example                |
        +-------------+-----------------+-----------------------+
    

    Modify your theme's CSS and use the :nth-child CSS pseudo-selector.

    td:nth-child(1) {
        width: 20%;
    }
    td:nth-child(2) {
        width: 30%;
    }
    td:nth-child(3) {
        width: 50%;
    }
    

    The output from the first option is the following:

    <table border="1" class="colwidths-given docutils" id="id1">
    <caption><span class="caption-text">This is my table</span><a class="headerlink" href="#id1" title="Permalink to this table">¶</a></caption>
    <colgroup>
    <col width="20%">
    <col width="30%">
    <col width="50%">
    </colgroup>
    <tbody valign="top">
    <tr class="row-odd"><td>Field type</td>
    <td>Description</td>
    <td>Example</td>
    </tr>
    </tbody>
    </table>