简体   繁体   English

CSS - 仅在具有单元格间距的表内的边框

[英]CSS - Border only inside the table with the cell spacing

I am trying to figure out how to add border only inside the table with the cell spacing. 我试图弄清楚如何只在表格内添加边框与单元格间距。 When I do: 当我做:

table {
  border-collapse: collapse;
  border-spacing: 4px;
}
table td, table th {
  border: 1px solid black;
}

It works almost fine just cells without spacing. 只有没有间距的细胞几乎可以正常工作。 How to achieve that? 怎么实现呢?

Thanks 谢谢

If you're trying to write CSS rules for tables on which you've defined the cellspacing attribute, a solution could be this : 如果您正在尝试为已定义cellspacing属性的表编写CSS规则,则可以使用以下解决方案:

table[cellspacing] {
  border-collapse: collapse;
  border-spacing: 4px;
}
table[cellspacing] td, table[cellspacing] th {
  border: 1px solid black;
}

But it would be much cleaner and more efficient to give a class to your table ( <table class="withspace"> ). 但是为表提供一个类会更清晰,更有效( <table class="withspace"> )。 So you would more classically do 所以你会更经典地做

table.withspace {
  border-collapse: collapse;
  border-spacing: 4px;
}
table.withspace td, table.withspace th {
  border: 1px solid black;
}

EDIT : just in case, if what you want is simply to have some space in your cells, add a padding value in your css : 编辑:以防万一,如果您想要的只是在您的单元格中有一些空格,请在您的CSS中添加填充值:

table {
  border-collapse: collapse;
  border-spacing: 4px;
}
table td, table th {
  border: 1px solid black;
  padding: 4px;
}

The CSS code posted is correct and causes borders around cells (but around the table as a whole) and 4px spacing between cells, on conforming browsers. 发布的CSS代码是正确的,并且在符合标准的浏览器上导致单元格周围的边界(但在整个表格周围)和单元格之间的4px间距。 I suppose you were testing this on IE 7 or older, which do not support the border-spacing property. 我想你是在IE 7或更早版本上测试它,它不支持border-spacing属性。

I'm afraid there is no simpler workaround than to create a table without any borders and put an inner element inside each cell, making that cell occupy the entire cell except small margins, and draw borders around the inner elements. 我担心没有比创建没有任何边框的表更简单的解决方法,并在每个单元格中放置一个内部元素,使得该单元格占据除小边距之外的整个单元格,并在内部元素周围绘制边框。 This probably gets ugly, so I'd rather let the presentation on IE 7 be suboptimal. 这可能会变得很难看,所以我宁愿让IE 7上的演示文稿不够理想。

(For some reason, border-spacing does not seem to work in jsfiddle. Probably some general rule overrides a normal attempt to set the property.) (出于某种原因, border-spacing似乎在jsfiddle中不起作用。可能一些一般规则会覆盖设置属性的正常尝试。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM