Reputation: 2650
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?
Upvotes: 21
Views: 121273
Reputation: 174
In case nothing fixes it. move your <tr>
inside thead
to tbody
.
this was the only solution in my case since i had so many complications already.
Upvotes: 1
Reputation: 1826
By default, th
and td
should be aligned. If you want to leave it as default, just put display: unset
:
.tablestuff thead {
display: unset;
}
document.querySelector("thead").style.display = "unset";
To make the jQuery's $(".tablestuff thead").show()
method works, your css
needs to be defined like this:
.tablestuff thead[style*='display: block'] {
display: unset !important;
}
This is because .show()
will set the display
to block
by default. The above css
will set it back to unset
whenever it's set to block
.
Upvotes: 0
Reputation: 54846
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:
Upvotes: 44
Reputation: 768
To set same width for table header and table body in table:
<table style="table-layout:fixed">
Upvotes: 5
Reputation: 977
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;
}
Upvotes: -1
Reputation: 5847
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.
Upvotes: 0
Reputation: 9174
The problem is caused by the display:block
in the style attribute for the thead.
Change it to display:table-header-group
Upvotes: 12
Reputation: 3959
When you want to show the thead element use this value: display: table-header-group;
Upvotes: 5