tardis
tardis

Reputation: 1360

CSS table: fixed header and same column width for <td> and <th>

I want a pure CSS solution with a fixed table header and same column width for <th> and <td> with different content. I have taken an example and modified it to get column with different content: http://jsfiddle.net/jd72op9n/4/

table tbody,table thead {
  display: block; /* comment to get same column with*/
}
table tbody {
  overflow: auto;
  height: 100px;
}

It seems that I cannot have both:

  1. If take http://jsfiddle.net/jd72op9n/4/ I get a fixed header but the columns for th and td are not the same.
  2. If I remove "display: block", I get the correct column but not fixed header.

Do you have a solution to get both?

Upvotes: 3

Views: 7780

Answers (2)

Nirpendra Patel
Nirpendra Patel

Reputation: 679

http://jsfiddle.net/patelnirpendra/2bs886p0/

css :

table tbody,table thead {
  display: block;
}

table{
    border: 1px solid black;
    table-layout: fixed;
}

th, td {
    border: 1px solid black;
    overflow: hidden;
    width: 150px;
}

Upvotes: 0

Kristijan Iliev
Kristijan Iliev

Reputation: 4987

I guess the only way is to strictly specify the width of the cells like this:

table th, table td{
  width: 80px;
}
tbody{
  width: 100%;
  margin-right: 20px;
}

Please try this fiddle

And if you want to change width to certain cell, for example the 4th with the long text, you can add this css rule:

th:nth-child(4), td:nth-child(4){
  width: 120px;
}

Upvotes: 1

Related Questions