問題描述

這個問題的答案需要更新,因為瀏覽器已經改變了


原來的問題

我看過 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 的 bottom-right 角上。

你怎麼建議我去做那個?

最佳解決方案

如果你給你的 TD 的高度為 1px,那麼子 div 將有一個高度的父代來計算它的%。因為你的內容會大於 1px,所以 td 會自動增長,和 div 一樣。 Kinda 一個垃圾駭客,但我敢打賭它會工作。

次佳解決方案

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 設置 di​​v 的高度

如果您將<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());
});

第三種解決方案

你可以嘗試使你的 div 浮動:

.thatSetsABackgroundWithAnIcon{

    float:left;
}

另外,使用 inline-block:

.thatSetsABackgroundWithAnIcon{

    display:inline-block;
}

inline-block 方法的工作實例:



table,
th,
td {
  border: 1px solid black;
}
<table>
  <tr>
    <td>
      <div style="border:1px solid red; height:100%; display:inline-block;">
        I want cell to be the full height
      </div>
    </td>
    <td>
      This cell
      <br/>is higher
      <br/>than the
      <br/>first one
    </td>
  </tr>
</table>

第四種方案

這個問題已經回答了 here 。將 height: 100% 放在 div 和容器 td 中。

參考文獻

注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇