我已经试了几个月,但是谷歌没有帮到我。我想在表格的<td>
和<th>
标签之间增加间距,但是当我这么做时,会使得表格外围也出现间距。因此,表格与其他内容不在同一行上,看起来就像表格有一些填充。
我似乎找不到解决方案。
这里提供了一个示例
我已经试了几个月,但是谷歌没有帮到我。我想在表格的<td>
和<th>
标签之间增加间距,但是当我这么做时,会使得表格外围也出现间距。因此,表格与其他内容不在同一行上,看起来就像表格有一些填充。
我似乎找不到解决方案。
这里提供了一个示例
我使用透明边框对解决方案进行了优化,因此不再具有倾斜的内边框。
1)让表格水平填充并折叠边框:
table {
width: 100%;
border-collapse: collapse;
}
2)将表格单元格的所有边框宽度设置为0,并防止在边框下方绘制背景。
td {
border: 0px solid transparent;
background-clip: padding-box;
}
3) 使用透明边框设置内部空白,但不包括第一行和第一列。
tr > td + td {
border-left-width: 10px;
}
tr + tr > td {
border-top-width: 10px;
}
这里有一个jsbin
我遇到了同样的问题,边框间距属性也会在表格周围添加空白。据我所知,没有任何方法可以将其限制在“内部”,因此我使用了透明边框代替:
table td {
border-left: 1em solid transparent;
border-top: 1em solid transparent;
}
这将‘border spacing’设置为正常,但在表格的顶部和左侧存在‘不需要的’间距。
table td:first-child {
border-left: 0;
}
选择第一列。
table tr:first-child td {
border-top: 0;
}
选择第一行的td元素(假设表格顶部以tr元素开始,如果是th元素则相应更改)。background-clip: padding-box;
,它可以正常工作。没有背景绘制在边框下方(背景延伸到填充的外沿)。 - TLindig我找到了一种方法,可以通过使用负边距来实现,并且在Steven的答案上进行了改进,因为它可以让你即使没有足够的内容也能使表格占用100%。解决方案是将表格宽度设置为100%,并在包含元素上使用负边距:
#container {
margin: 0 -10px;
}
table {
border-collapse: separate;
border-spacing: 10px;
}
td, th {
background-color: #ccf;
padding: 5px;
}
div
包装了它所以才生效了,但对于表格本身,两侧的负边距不起作用。我没有解释清楚,我的错。 - vsync与Steven Vachon所说的类似,负边距可能是最好的选择。
另外,您可以使用calc()
来解决问题。
CSS:
/* border-collapse and border-spacing are css equivalents to <table cellspacing="5"> */
.boxmp {
width:100%;
border-collapse:separate;
border-spacing:5px 0;
}
/* border-spacing includes the left of the first cell and the right of the last cell
negative margin the left/right and add those negative margins to the width
ios6 requires -webkit-
android browser doesn't support calc()
100.57% is the widest that I could get without a horizontal scrollbar at 1920px wide */
.boxdual {
margin:0 -5px;
width:100.57%;
width:-webkit-calc(100% + 10px);
width:calc(100% + 10px);
}
只需加上您减少的任何边距,否则宽度将太窄(100%不够宽)。
table {
border-collapse: inherit;
border-spacing: 10px;
width: calc(100% + 20px);
margin-left: -10px;
}
使用margin-left: -10px;
可以去掉左边的填充,但右边会有20像素的填充。现在要更新它,请使用width: calc(100% + 20px);
#container {
box-sizing: border-box; /* avoids exceeding 100% width */
margin: 0 auto;
max-width: 1024px;
padding: 0 10px; /* fits table overflow */
width: 100%;
}
table {
border-collapse: separate;
border-spacing: 10px;
margin: 0 -10px; /* ejects outer border-spacing */
min-width: 100%; /* in case content is too short */
}
td {
width: 25%; /* keeps it even */
}
请确保您有足够的内容来展开表格以达到100%的宽度,否则将会比实际宽度窄20像素。
HTML
<div class="column-container">
<div class="column-children-wrapper">
<div class="column">One</div>
<div class="column">Two</div>
<div class="column">Three</div>
<div class="column">Four</div>
</div>
</div>
CSS
.column-container {
display: table;
overflow: hidden;
}
.column-children-wrapper {
border-spacing: 10px 0;
margin-left: -10px;
margin-right: -10px;
background-color: blue;
}
.column {
display: table-cell;
background-color: red;
}