【问题标题】:How to wrap the border of a table around rows that are not full?如何将表格的边框包裹在未满的行周围?
【发布时间】:2018-02-04 00:36:29
【问题描述】:

我想创建一个由多行中的多个单元格组成的表格,当单元格的数量不适合表格大小的 100% 时,主表格的边框不会显示为精确的正方形,而是换行围绕内容本身。

例如:

<table border = "2px">
    <tr>
        <td>1</td><td>2</td>
    </tr>
    <tr>
        <td>3</td>
     </tr>
</table>

这是目前的情况:

这就是我的目标:

【问题讨论】:

  • 你可能不应该使用表格。
  • 你不能在桌子上这样做,我认为你根本不能这样做。
  • 一个小技巧,把你的 HTML 放在 body 标签里面,而不是放在它后面。
  • 哎呀,显然我应该把内容放在正文中^_^

标签: html css html-table border


【解决方案1】:

您可以通过包含冗余单元格并使用 CSS empty-cells 属性隐藏它们来实现此目的。

HTML

<table border="0" cellspacing="0" cellpadding="0">
    <tr>
        <td>1</td>
        <td>2</td>
    </tr>
    <tr>
        <td>3</td>
        <td></td>
    </tr>
</table>

CSS

table td {empty-cells:hide;border:3px double;}

注意表格本身没有给定边框,而是直接给单元格本身。不幸的是,这不能与 border-collapse:collapse; 声明结合使用。

jsFiddle demo


编辑

如果需要第二个边框,您可以使用border-style 属性的double 值。更新了上面的 CSS 和 fiddle 以反映这一点。

【讨论】:

  • 有趣的选择,但是它仍然会删除想要的外部边框。感谢您的回复。
  • @JacobCohen 用第二个边框更新了答案。不确定这正是您的意思,但它在视觉上达到了类似的效果。
【解决方案2】:

有可能!

通过英勇的个人努力,我仅使用您的 html 中的 css 复制了您的图形。

http://codepen.io/anon/pen/Ekoxl

它是这样工作的:

table {
  display: block;
}

tr {
  display: block;
  float: left;
  clear: left;
  position: relative;
  border-style: solid;
  border-width: 3px;
  background-color: white;
  border-color: #999 #333 #333 #999;
}
tr:nth-child(n+2) {
  border-width: 0 3px 3px 3px;
}
tr:nth-child(n+2)::before {
  content: "";
  display: block;
  background-color: #fff;
  position: absolute;
  width: 100%;
  top: -3px;
  height:4px;
}
tr:nth-child(n+2)::after {
  content: "";
  display: block;
  background-color: #999;
  position: absolute;
  width: 3px;
  height: 4px;
  top: -3px;
  left: -3px;
}

td {
  display: inline-block;
  border: solid #666 1px;
  margin: 2px
}

【讨论】:

  • 非常好!我能看到的唯一警告是,这完全是 CSS3。
  • 嗯,是的,我必须做一些激烈的体操才能让它发挥作用。我很惊讶它完全可以工作。我猜 CSS3 是你必须为锯齿状表格行付出的代价。
【解决方案3】:

你不能通过 table 做到这一点,但可以通过 div 和 css 来实现

我仍然展示了 td with little style 可以做什么

请检查

<html>
<head>
<style>
td{border:2px solid black;}
</style>
</head>
<body>
<table border = "2px">
<tr><td>1</td><td>2</td></tr><tr><td>3</td></tr>
</table>
<br/>
<table cellspacing="0" cellpadding="1">
<tr><td>1</td><td>2</td></tr><tr><td>3</td></tr>
</table>
</body>
</html>

【讨论】:

  • 这基本上去除了外边框。这不是我的目标。感谢回复!
猜你喜欢
  • 2011-08-05
  • 2012-08-02
  • 2013-01-07
  • 2020-10-18
  • 1970-01-01
  • 2015-05-09
  • 1970-01-01
  • 1970-01-01
  • 2018-09-08
相关资源
最近更新 更多