CSS表边框间距只在里面

use*_*081 48 css html-table

我试图解决这个问题好几个月了,谷歌并没有帮助我.我试图在表格<td><th>标签之间设置间距,但是当我这样做时,它会在外面间隔.因此,该表与其他任何内容都不一致.所以看起来桌子有一些填充.

我似乎无法找到解决方案.

是一个问题的例子

Jum*_*omp 21

有同样的问题,边框间距属性也是在桌子周围添加空间,据我所知,无论如何也没有将它限制为只有'内部',所以我使用透明边框代替:

table td {
   border-left: 1em solid transparent;
   border-top: 1em solid transparent;
}
Run Code Online (Sandbox Code Playgroud)

这将"边框间距"设置为正常,除了表格的顶部和左侧有"不需要的"间距.

table td:first-child {
   border-left: 0;
}
Run Code Online (Sandbox Code Playgroud)

选择第一列.

table tr:first-child td {
   border-top: 0;
}
Run Code Online (Sandbox Code Playgroud)

选择第一行的td元素(假设表的顶部以tr元素开头,相应地更改为th).

  • 虽然这是一个聪明的伎俩,但对于已经使用边框属性进行单元格样式设置的人来说,这并不是很有用. (5认同)

Mar*_*ber 15

我找到了一种方法来做到这一点,利用负边距并改进了史蒂文的答案,因为它可以使表格占据100%,即使它没有足够的内容.解决方案是使表宽度为100%并在包含元素上使用负边距:

#container {
    margin: 0 -10px;
}
table {
    border-collapse: separate;
    border-spacing: 10px;
}
td, th {
    background-color: #ccf;
    padding: 5px;
}
Run Code Online (Sandbox Code Playgroud)

将其视为jsFiddle


TLi*_*dig 12

我使用透明边框优化了解决方案,因此不再倾斜切割内边框.

1)让表填充水平并折叠边框:

table {
  width: 100%;
  border-collapse: collapse;
}
Run Code Online (Sandbox Code Playgroud)

2)将表格单元格的所有边框设置为宽度0,并防止在边框下方绘制背景.

td {
  border: 0px solid transparent;
  background-clip: padding-box;
}
Run Code Online (Sandbox Code Playgroud)

3)使用透明边框设置内部空间,但不设置第一行和第二列.

tr > td + td {
  border-left-width: 10px;
}

tr + tr > td {
  border-top-width: 10px;
}
Run Code Online (Sandbox Code Playgroud)

这是一个jsbin


dou*_*leJ 9

与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);
}
Run Code Online (Sandbox Code Playgroud)

只需添加你起飞的边距或宽度太窄(100%不够宽).