Search code examples
htmlcsshtml-tablewidthcolumn-width

setting width of a td element using CSS id


I am developing an app in Django.

I am trying to set the width of the last column of my table equal to 10 pixels.

So I tryed by both including style="width: 10 px" in the td element and by using a CSS file that targets the id attribute given to the td element.

Here is my CSS file content (it's properly liked to my template, I am sure):

#url_cell{
  width: 10px;
}

And here is my template:

<table>

    <tr style="font-weight: bold; text-align: center;width:100px">

        <td class="class_Tabella_Head">Lemma</td>
        <td class="class_Tabella_Head">Acronimo</td>
        <td class="class_Tabella_Head">Definizione</td>
        <td class="class_Tabella_Head">Titolo documento fonte</td>
        <td id="url_cell" style="width: 10 px" class="class_Tabella_Head">URL documento fonte</td>

    </tr>

{% for row in queryresult_key %}

    <tr>        

        <td class="class_Tabella_Risultati">{{ row.0 }}</td>
        <td class="class_Tabella_Risultati">{{ row.1 }}</td>
        <td class="class_Tabella_Risultati">{{ row.2 }}</td>
        <td class="class_Tabella_Risultati">{{ row.3 }}</td>
        <td id="url_cell" style="width: 10 px" class="class_Tabella_Risultati">{{ row.4 }}</td>

    </tr>

{% endfor %}

</table>

Solution

  • table {
      table-layout: fixed;
      width: 400px;
      border-collapse: collapse;
    }
    
    table tr td {
      border: 1px solid;
    }
    
    table tr td:last-child {
      width: 10px;
      background-color: red;
    }
    <table>
    
      <tr style="font-weight: bold; text-align: center">
    
        <td class="class_Tabella_Head">Lemma</td>
        <td class="class_Tabella_Head">Acronimo</td>
        <td class="class_Tabella_Head">Definizione</td>
        <td class="class_Tabella_Head">Titolo documento fonte</td>
        <td class="class_Tabella_Head">URL documento fonte</td>
    
      </tr>
    
    
    </table>

    You can use :last-child selector to access last element from the list:

    table tr td:last-child { width: 10px }
    

    UPDATE:
    As Bryan Elliott mentioned you also need to add fixed layout to table:

    table { table-layout: fixed; }