【问题标题】:How to have vertical line between table cells?如何在表格单元格之间有垂直线?
【发布时间】:2021-04-01 16:02:58
【问题描述】:

在下面的代码中,我想在单元格之间设置垂直线,最好的方法是什么?我尝试过为表格提供背景颜色,但它与为表格单元格提供边框相同,然后尝试使用左边框或右边框,但它会在单元格外多出一行。在这里,我想要单元格之间的垂直线。请帮忙。

table tr td {
  background-color: #dedede;
  color: black
}
<table>
  <tr>
    <td>this is first cell</td>
    <td>this is second cell</td>
    <td>this is third cell</td>
  </tr>
  <tr>
    <td>this is fouth cell</td>
    <td>this is fifth cell</td>
    <td>this is sixth cell</td>
  </tr>
</table>

【问题讨论】:

  • 查找第一个孩子/最后一个孩子

标签: html css


【解决方案1】:

像这样?这会为每个table tr td 添加一个边框,除了行中的最后一个

table tr td {
  border-right: 1px solid blue;
  color: black
}

table tr td:last-of-type {
  border: none;
}
<table>
  <tr>
    <td>this is the first cell</td>
    <td>this is the second cell</td>
    <td>this is the third cell</td>
  </tr>
  <tr>
    <td>this is the fourth cell</td>
    <td>this is the fifth cell</td>
    <td>this is the sixth cell</td>
  </tr>
</table>

正如 Daniel A. White 所述 - last-child 也有效:

table tr td:last-child {
  border: none;
}

【讨论】:

  • 你也可以添加table {border-collapse: collapse;} 这样你会得到jsfiddle.net/Lg0wyt9u/6之间没有空格的行
【解决方案2】:

您可以将 CSS 边框应用到您的 td 并添加 cellspacing="0" cellpadding="0" 以消除 td 之间的间隙

HTML:

<table cellspacing="0" cellpadding="0">
  <tr>
    <td>this is first cell</td>
    <td>this is second cell</td>
    <td>this is third cell</td>
  </tr>
  <tr>
    <td>this is fouth cell</td>
    <td>this is fifth cell</td>
    <td>this is sixth cell</td>
  </tr>
</table>

CSS:

table{
  padding: 0;
  background-color: #dedede;
  color: black;
}
table tr td{
  padding: 5px;
  border-right: 1px solid red;
}
table tr td:last-child{
  border-right: none;
}

小提琴:https://jsfiddle.net/debraj/1ehubox9/

【讨论】:

    【解决方案3】:
    table tr td {
       border-right: 1px solid black;
    }
    table tr td:nth-child(3n){
        border-right: none;
    }
    

    【讨论】:

      【解决方案4】:

      在单元格右侧添加边框并在表格左侧添加边框应该这样做:

      table tr td {
        border-right: 1px solid #dedede;
        color: black
      }
      
      table {
        border-left: 1px solid #dedede;
      }
      <table>
        <tr>
          <td>this is first cell</td>
          <td>this is second cell</td>
          <td>this is third cell</td>
        </tr>
        <tr>
          <td>this is fouth cell</td>
          <td>this is fifth cell</td>
          <td>this is sixth cell</td>
        </tr>
      </table>

      【讨论】:

      • 正如我所说的不在外面的单元格之间的垂直线。
      【解决方案5】:

      table tr td+td {
        border-left: 1px solid blue;
        color: black
      }
      <table>
        <tr>
          <td>this is first cell</td>
          <td>this is second cell</td>
          <td>this is third cell</td>
        </tr>
        <tr>
          <td>this is fouth cell</td>
          <td>this is fifth cell</td>
          <td>this is sixth cell</td>
        </tr>
      </table>

      【讨论】: