我在尝试使用CSS将表嵌入现有HTML页面时遇到问题。
默认情况下,这个CSS使用如下样式定义来隐藏表的标题:
.tablestuff thead {
display: none;
}
但我想让表显示出来,所以我尝试用"display:block"(用javascript)设置thead元素的样式。这会显示标题,但标题的列不会与td列对齐。
我已经将我的HTML简化为以下内容(希望能尽量减少打字错误),并在thead元素上显示由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>
如何既显示标题又使其与td列正确对齐?
CSS包含比常用的none
、inline
、inline-block
和block
更多的显示模式。事实上,有不少。
在这种情况下,您要使用的不是display:block;
而是display:table-header-group;
。
以下是应用于您的表的不同样式的一些示例:
http://jsfiddle.net/CrYdz/1
问题是由thead的样式属性中的display:block
引起的。
将其更改为display:table-header-group
当您想要显示thead元素时,请使用以下值:display: table-header-group;
要为表中的表头和表体设置相同的宽度:
<table style="table-layout:fixed">
如果没有任何修复方法,请将<tr>
从thead
移动到tbody
。
这是我唯一的解决方案,因为我已经有很多并发症了。
也许THs的内容比TDs的内容宽,而实际上宽度并不是设置的20px。
因此,因为您首先加载的页面没有thead,所以该表将获得TD的宽度。然后,当您通过js显示THEAD时,表的宽度仍然相同,但THs的宽度可能不同。
默认情况下,th
和td
应该对齐。如果您想将其保留为默认值,只需输入display: unset
:
.tablestuff thead {
display: unset;
}
纯JavaScript:
document.querySelector("thead").style.display = "unset";
jQuery:
为了使jQuery的$(".tablestuff thead").show()
方法起作用,您的css
需要这样定义:
.tablestuff thead[style*='display: block'] {
display: unset !important;
}
这是因为默认情况下.show()
会将display
设置为block
。只要设置为block
,上述css
就会将其设置回unset
。
使用css 显示和隐藏th而不是thead
/* to hide */
.tablestuff thead th{
display: none;
}
/* to show */
.tablestuff thead th{
display: table-cell;
}