如何让<div>填充<td>高度

新手上路,请多包涵

我浏览了 StackOverflow 上的几篇文章,但未能找到这个相当简单的问题的答案。

我有一个这样的 HTML 结构:

 <table>
  <tr>
    <td class="thatSetsABackground">
      <div class="thatSetsABackgroundWithAnIcon">
        <dl>
          <dt>yada
          </dt>
          <dd>yada
          </dd>
        </dl>
      <div>
    </td>
    <td class="thatSetsABackground">
      <div class="thatSetsABackgroundWithAnIcon">
        <dl>
          <dt>yada
          </dt>
          <dd>yada
          </dd>
        </dl>
      <div>
    </td>
  </tr>
</table>

我需要的是 div 填充 td 的高度,这样我就可以将 div 的背景(图标)定位在 td 的右下角 ---

你建议我怎么做?

原文由 user191152 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 724
2 个回答

如果你给你的 TD 一个 1px 的高度,那么子 div 将有一个高度的父级来计算它的百分比。因为您的内容会大于 1px,所以 td 会自动增长,div 也是如此。有点像垃圾黑客,但我敢打赌它会奏效。

原文由 psayre23 发布,翻译遵循 CC BY-SA 2.5 许可协议

CSS height: 100% 仅在元素的父元素具有明确定义的高度时才有效。例如,这将按预期工作:

 td {
    height: 200px;
}

td div {
    /* div will now take up full 200px of parent's height */
    height: 100%;
}

因为它看起来像你的 <td> 将是可变高度,如果你添加右下角的图标和绝对定位的图像,如下所示:

 .thatSetsABackgroundWithAnIcon {
    /* Makes the <div> a coordinate map for the icon */
    position: relative;

    /* Takes the full height of its parent <td>.  For this to work, the <td>
       must have an explicit height set. */
    height: 100%;
}

.thatSetsABackgroundWithAnIcon .theIcon {
    position: absolute;
    bottom: 0;
    right: 0;
}

像这样使用表格单元格标记:

 <td class="thatSetsABackground">
  <div class="thatSetsABackgroundWithAnIcon">
    <dl>
      <dt>yada
      </dt>
      <dd>yada
      </dd>
    </dl>
    <img class="theIcon" src="foo-icon.png" alt="foo!"/>
  </div>
</td>

编辑:使用 jQuery 设置 div 的高度

如果您将 --- 保留为 <div> 的子 <td> ,则此 jQuery 片段将正确设置其高度:

 // Loop through all the div.thatSetsABackgroundWithAnIcon on your page
$('div.thatSetsABackgroundWithAnIcon').each(function(){
    var $div = $(this);

    // Set the div's height to its parent td's height
    $div.height($div.closest('td').height());
});


原文由 Pat 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题