CSS border-collapse 属性的使用方法

CSS border-collapse 属性的使用方法

CSS border-collapse 属性的使用方法

border-collapse 属性用于设置表格中单元格边框的合并方式。该属性主要有两个值:separate 和 collapse,分别表示分离边框和合并边框。以下是详细的使用方法:

语法

table { border-collapse: separate | collapse; }

值说明

  • separate(默认值):边框是分离的,每个单元格都有自己的边框,单元格之间的间距由 cellspacing 或 border-spacing 属性控制(在 HTML 中使用 cellspacing,而在 CSS 中使用 border-spacing)。
  • collapse:边框是合并的,相邻单元格共享一条边框,不会出现双重边框的情况。此时,cellspacing 和 border-spacing 属性将不起作用。

示例代码

使用 separate 值
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Border Separate Example</title> <style> table { border-collapse: separate; border-spacing: 10px; /* 设置单元格之间的间距 */ } th, td { border: 2px solid black; padding: 10px; } </style> </head> <body> <table> <tr> <th>Header 1</th> <th>Header 2</th> </tr> <tr> <td>Data 1</td> <td>Data 2</td> </tr> </table> </body> </html>

在这个例子中,表格的边框是分开的,并且单元格之间有 10 像素的间距。

使用 collapse 值
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Border Collapse Example</title> <style> table { border-collapse: collapse; } th, td { border: 2px solid black; padding: 10px; } </style> </head> <body> <table> <tr> <th>Header 1</th> <th>Header 2</th> </tr> <tr> <td>Data 1</td> <td>Data 2</td> </tr> </table> </body> </html>

在这个例子中,表格的边框是合并的,相邻单元格之间只有一条边框线。

注意事项

  • 当使用 border-collapse: collapse 时,如果单元格没有设置边框样式或宽度,那么这些单元格之间将不会有边框显示。
  • 在某些情况下,你可能需要为特定的单元格或表头设置不同的边框样式或颜色,这时可以通过对单独的 <th> 或 <td> 元素应用额外的 CSS 规则来实现。

通过合理使用 border-collapse 属性,你可以更好地控制表格的外观和布局,使其更符合你的设计需求。