负边距在表格中的奇怪现象

6
这个问题并不是很短,但很容易理解。
这里是jsFiddle
我有两个嵌套的表格,像这样:

enter image description here

这里是标记:

<table class="outer">
  <tr>
    <td></td>
    <td>
      <table class="inner">
        <tr>
          <td></td>
          <td></td>
          <td></td>
        </tr>
      </table>
    </td>
    <td></td>
  </tr>
</table>

<style>
table, tr, td {
  border: 1px solid black;
  border-collapse: collapse;
}

table {
  width: 100%;
}

.outer {
  height: 100px;
}

.inner {
  background-color: #ccc;
  height: 50px;
}
</style>

第一件奇怪的事情

然后,我想给内部表格添加一个负的水平边距:

.inner {
  margin: 0 -10%;
}

预期输出应该像这样:

enter image description here

但是,我得到了这个:

enter image description here

问题可以通过将内部表格放置在 div 中来解决:
<!-- outer table -->
  <div class="wrapper">
    <table class="inner-wrapped">
      <tr>
        <td></td>
        <td></td>
        <td></td>
      </tr>
    </table>
  </div>
<!-- outer table -->

<style>
.wrapper {
  margin: 0 -10%;
}

.inner-wrapped {
  background-color: rgb(0,200,0);
  height: 50px;
}
</style>

第二个奇怪的事情

如果我将水平负边距设为-10px(之前我们使用百分比而不是像素),那么除了表格向左移动(就像第一种情况一样),它的宽度也会显著减小:

.inner {
  margin: 0 -10px;
}

enter image description here

问题

  • 为什么会发生这些奇怪的事情?

  • 有什么解决方法吗?像我所做的那样简单地使用包装器是一个好的实践方法,还是应该使用另一种更聪明的方法?


在 Chrome 的检查器中,查看描述宽度、填充和边距的嵌套框(白色、橙色和绿色),这样会更容易理解。 - Ibu
因为table-layout: auto没有被规范完全定义,它的实现取决于具体情况。浏览器会尝试考虑内容,但在您的情况下,这会导致大量循环定义。不要依赖结果。如果您想要一个明确定义的算法,可以尝试table-layout: fixed - Oriol
@Oriol 谢谢,很有趣。 - john c. j.
1个回答

4

如果主表格的width:100%;,它将会扩展到最大,内部表格将以初始的100%作为参考。只有当内容到达时,负边距才会使其扩展。 如果满足以下条件,则可以正常工作:https://jsfiddle.net/md2tx2d4/2/

.inner { margin:0 -10%; width:120%;}   

如果您不设置宽度,并让内容自然增长,则可以实现此效果。
table { }
td {width:200px;/* instead real content missing here */}

https://jsfiddle.net/md2tx2d4/1/


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接