You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用CSS为React中表格的tbody tr设置边框样式

How to Properly Add Border Styles to <tbody> and <tr> in React Tables

The reason your border styles on <tr> and <tbody> aren't showing up boils down to how HTML tables handle border rendering by default. Let me break this down and show you the fix:

Why Your Initial Attempt Failed

By default, HTML tables use border-collapse: separate;. In this mode, browsers prioritize rendering borders on <td> elements over <tr> or <tbody>—the row/container borders either get hidden behind cell borders or don't render at all. That's why styling <td> worked immediately, but your <tr>/<tbody> styles were ignored.

The simplest and most reliable way to make <tr> or <tbody> borders visible is to first set border-collapse: collapse; on the parent <table> element. This merges adjacent borders together, allowing row/container borders to render properly.

Here's how to implement this with your React code:

Step 1: Add CSS Styles

/* Target your table with a class for specificity */
.user-table {
  border-collapse: collapse;
  width: 100%; /* Optional: Makes the table fill its container */
}

/* Style the table rows */
.user-table tbody tr {
  border: 1px solid gray;
}

/* Optional: If you only want bottom borders between rows (common for list-style tables) */
.user-table tbody tr:not(:last-child) {
  border-bottom: 1px solid gray;
}

/* Style the tbody container if needed */
.user-table tbody {
  border: 2px solid darkgray; /* Thicker border around the entire tbody */
}

Step 2: Update Your React Component

Add the className to your <table> element:

<table className="user-table">
  <tbody>
    <tr>
      <td>lendsqr</td>
      <td>{props.username}</td>
      <td>{props.email}</td>
      <td>{props.phoneNumber}</td>
      <td>{props.dateJoined}</td>
      <td>{props.status}</td>
    </tr>
  </tbody>
</table>

Fix 2: Avoid display: block (Don't Do This!)

You might see suggestions to set display: block; on <tr>, but this breaks the table's native layout system. Your columns will lose their automatic sizing, and the table will behave like a regular block element instead of a structured table. Stick with border-collapse for consistent results.

Key Takeaways

  • Always start with border-collapse: collapse; on the <table> to unlock border styling for <tr> and <tbody>.
  • Use specific classes to target your table (instead of global selectors) to avoid interfering with other tables in your app.
  • Adjust border properties (like border-bottom instead of full border) to match your design needs.

内容的提问来源于stack exchange,提问作者Freddy Castano

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 01:07:28