How to align TH Header with TD in TBody

I'm having problems trying to embed a table in an existing HTML page with some CSS.

This CSS is hiding the header of the table by default with a style definition like:

.tablestuff thead {
     display: none;
}

But I want the table to show, so I tried setting the style on the thead element with "display:block" (with javascript). That makes the header display, but the columns of the header don't line up with the td columns.

I have reduced my HTML to the following (hopefully with minimal typos) and showing the style on the thead element as set by javascript.

<div class="tablestuff">
<table border="1">
<thead style="display:block">
<tr>
<th id="th1" style="width: 20px"></th>
<th id="th2" style="width: 20px"></th>
</tr>
</thead>
<tbody>
<tr>
<td headers="th1" style="width: 20px"></td>
<td headers="th2" style="width: 20px"></td>
</tr>
</tbody>
</table>
</div>

How can I make both the header show and also align correctly with the td columns?

Answers


CSS includes more display modes than the commonly used none, inline, inline-block, and block. There are quite a few, in fact.

In this case, it appears what you want to use instead of display:block; is display:table-header-group;.

Here are some examples of the different styles, as applied to your table:

http://jsfiddle.net/CrYdz/1


The problem is caused by the display:block in the style attribute for the thead.

Change it to display:table-header-group


To set same width for table header and table body in table:

<table style="table-layout:fixed">

When you want to show the thead element use this value: display: table-header-group;


Maybe the content of the THs is wider than the content of the TDs and in reality the width is not 20px as set.

So, because you first load the page without the thead, the table gets the width of the TDs. Then, when you display the THEAD by js, the table width continues being the same but probably the THs have different width.


show and hide th instead of thead with the css

/* to hide */
.tablestuff thead th{
     display: none;
}

/* to show */
.tablestuff thead th{
     display: table-cell;
}

Need Your Help

Access CanCan's `can?` method from a model

ruby-on-rails cancan

You can get the current_user's permissions from a view or controller using can? in this fashion:

Javascript: How to copy all options from one select element to another?

javascript html select option

How can I copy all options of one select element to another? Please give me the easiest way, I'm allergic to looping.