Echchama Nayak
Echchama Nayak

Reputation: 933

Table rows not aligning

I have two tables in the following fiddle. The rows are not aligned to the header. This is my code for first table

<table class=" table-bordered">
    <tr>
        <th>Doc Name:</th>
        <th>Atom Type:</th>
        <th>Cluster Method:</th>
        <th>k:</th>
        <th>
            <small>Stylistic Feature(s):</small>
        </th>
    </tr>
    <tr>
        <td style="font-size: 10px;">rowling_and_dickens</td>
        <td style="font-size: 10px;">sentence</td>
        <td style="font-size: 10px;">kmeans</td>
        <td style="font-size: 10px;">2</td>
        <td style="font-size: 10px;">hapax_dislegomena;honore_r_measure;hapax_legomena;</td>
    </tr>
</table>

The other table follows a similar pattern. I am not adding them here due to paucity of space.

https://jsfiddle.net/fk6fnto4/

My table rows do not get aligned properly no matter what I do. I have looked at many solutions and modified the code accordingly, to no avail. Please help me identify what is wrong here.

Upvotes: 0

Views: 8932

Answers (1)

John Mellor
John Mellor

Reputation: 181

To make column content aligned, we need to set its width to be fixed. Currently each cell takes as much space as it needs. It seems that the first column should have the smallest width, and the third one should be widest. Other columns could be same width since they all contain 5 digit numbers. To set different td widths we could use different classes for each, but it could be messy, so we'll use nth-child() selector which looks like this:

td:nth-child(1) {
    width: 10%
}

This sets width of all td elements that are the first child of their parents to 10%. What you should do is add this to your style so it looks like this:

<style>
  .container {
    margin-left: 0;
  }

  tbody {
    display: block;
    max-height: 500px;
    overflow-y: scroll;
  }

  thead,
  tbody tr {
    display: table;
    width: 100%;
  }

  thead {
    width: 100%;
  }

  table {
    width: 200px;
  }

  td:nth-child(1) {
    width:10%
  }

  td:nth-child(3) {
    width:30%
  }

</style>

What this means is that the first column will take up 10% of tbody width, the third one will take up 30%, and others will use 20% each. However, if those can also contain data of variable length, you should add similar rules for them too.

This way, column content will be aligned to center. To set different alignment use text-align property.

Upvotes: 1

Related Questions