如何使<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。


您如何建议我去解决这个问题?


一只名叫tom的猫
浏览 1434回答 3
3回答

胡子哥哥

CSS高度:仅当元素的父级具有明确定义的高度时,才100%有效。例如,这将按预期工作:td {&nbsp; &nbsp; height: 200px;}td div {&nbsp; &nbsp; /* div will now take up full 200px of parent's height */&nbsp; &nbsp; height: 100%;}由于似乎您的<td>高度将是可变的,因此如果您在右下角的图标中添加了绝对定位的图像,该怎么办?.thatSetsABackgroundWithAnIcon {&nbsp; &nbsp; /* Makes the <div> a coordinate map for the icon */&nbsp; &nbsp; position: relative;&nbsp; &nbsp; /* Takes the full height of its parent <td>.&nbsp; For this to work, the <td>&nbsp; &nbsp; &nbsp; &nbsp;must have an explicit height set. */&nbsp; &nbsp; height: 100%;}.thatSetsABackgroundWithAnIcon .theIcon {&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; position: absolute;&nbsp; &nbsp; bottom: 0;&nbsp; &nbsp; right: 0;}像这样的表格单元格标记:<td class="thatSetsABackground">&nbsp;&nbsp;&nbsp; <div class="thatSetsABackgroundWithAnIcon">&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; <dl>&nbsp; &nbsp; &nbsp; <dt>yada&nbsp; &nbsp; &nbsp; </dt>&nbsp; &nbsp; &nbsp; <dd>yada&nbsp; &nbsp; &nbsp; </dd>&nbsp; &nbsp; </dl>&nbsp; &nbsp; <img class="theIcon" src="foo-icon.png" alt="foo!"/>&nbsp; </div></td>编辑:使用jQuery设置div的高度如果您将保留<div>为的子代,则<td>此jQuery片段将正确设置其高度:// Loop through all the div.thatSetsABackgroundWithAnIcon on your page$('div.thatSetsABackgroundWithAnIcon').each(function(){&nbsp; &nbsp; var $div = $(this);&nbsp; &nbsp; // Set the div's height to its parent td's height&nbsp; &nbsp; $div.height($div.closest('td').height());});

森林海

您可以尝试使div浮动:.thatSetsABackgroundWithAnIcon{&nbsp; &nbsp; float:left;}或者,使用内联块:.thatSetsABackgroundWithAnIcon{&nbsp; &nbsp; display:inline-block;}内联块方法的工作示例:table,th,td {&nbsp; border: 1px solid black;}<table>&nbsp; <tr>&nbsp; &nbsp; <td>&nbsp; &nbsp; &nbsp; <div style="border:1px solid red; height:100%; display:inline-block;">&nbsp; &nbsp; &nbsp; &nbsp; I want cell to be the full height&nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; </td>&nbsp; &nbsp; <td>&nbsp; &nbsp; &nbsp; This cell&nbsp; &nbsp; &nbsp; <br/>is higher&nbsp; &nbsp; &nbsp; <br/>than the&nbsp; &nbsp; &nbsp; <br/>first one&nbsp; &nbsp; </td>&nbsp; </tr></table>
打开App,查看更多内容
随时随地看视频慕课网APP