【问题标题】:Make div height 100% in a table cell [duplicate]在表格单元格中使 div 高度 100% [重复]
【发布时间】:2016-11-09 03:35:56
【问题描述】:

当行被另一个单元格中的自动换行拉伸时,如何使单元格表中的 div 达到 100% 高度。

在这个Fiddle 中,我想让第二个单元格中的 div 填充整个单元格(高度的 100%)。

td {
  border: 1px solid red;
  width: 50%;
  background-color: yellow;
}
td div {
  background-color: green;
  width: 100%;
  height: 100%;
  margin: 0;
  padding: 0;
}
<table>
  <tr>
    <td>
      <div>
        abcde abcde abcde abcde abcde abcde abcde abcde abcde abcde abcde abcde abcde abcde abcde abcde abcde abcde abcde abcde abcde abcde abcde abcde abcde abcde abcde abcde abcde abcde abcde abcde abcde abcde abcde abcde abcde abcde abcde abcde abcde abcde abcde abcde abcde abcde abcde abcde abcde abcde abcde abcde abcde abcde abcde abcde abcde abcde abcde abcde
      </div>
    </td>
    <td>
      <div>
        xxx
      </div>
    </td>
  </tr>
</table>

【问题讨论】:

    标签: html css html-table


    【解决方案1】:

    编辑

    正如下面的 cmets 所述,我的第一种方法 display: inline-block 在 Firefox 中不起作用。

    正如 progysm 提到的,使用 tr, td{height: 100%} 在所有浏览器上都能正常工作,请参阅小提琴 http://jsfiddle.net/3v4wz030/61/

    td div {
        background-color: green;
        width:100%;
        height: 100%;
        margin: 0;
        padding:0;
    }
     tr, td { height: 100%; } 
    

    下面的代码在 Firefox 中不起作用,我第一次尝试失败了

    只需添加display: inline-block 见小提琴http://jsfiddle.net/3v4wz030/39/

    td div {
        background-color: green;
        width:100%;
        height: 100%;
        display:inline-block;
        margin: 0;
        padding:0;
    }
    

    【讨论】:

    • 在我的浏览器(firefox)中,我需要输入 tr, td { height: 100%; } 与 td div { height: 100%; } 不需要内联块。
    • tr, td { height: 100%; } 实际上对我不起作用(不是小提琴 - 尝试过 Chrome 和 IE11)。 inline-block 有效,但 @Pangloss 答案(定位技巧)更适合我的情况,因为即使单元格有一些填充,它也会填满整个单元格。
    【解决方案2】:

    如果你只需要背景色覆盖整个单元格,你可以设置在td而不是div

    td:last-child {
      background-color: green;
    }
    

    如果您确实需要使div 覆盖单元格,您可以尝试使用position 技巧。请注意,此方法仅适用于第二个单元格中的数据较少时。

    td {
      position: relative;
    }
    td:last-child div {
      background-color: green;
      width:100%;
      height: 100%;
      position: absolute;
      left: 0;
      top: 0;
    }
    

    jsFiddle

    【讨论】:

    • 像魅力一样工作,谢谢!
    • 非常糟糕的解决方案。如果绝对 div 将大于表格单元格 - 内容将丢失 jsfiddle.net/9p58gLhg
    • @godblessstrawberry - 你可以使用溢出:自动;来解决这个问题。
    • @SolidSnake 对哪个元素有什么帮助?
    • @godblessstrawberry - 放在div上,超过宽度/高度就会变成可滚动的内容。
    猜你喜欢
    • 1970-01-01
    • 2016-12-14
    • 2012-04-14
    • 1970-01-01
    • 1970-01-01
    • 2017-12-24
    • 1970-01-01
    • 2013-03-19
    • 2015-03-09
    相关资源
    最近更新 更多