iT邦幫忙

0

內部div的高度,使用h-full卻無法獲取外部div的高度

  • 分享至 

  • xImage

大家好,
想請問大家,為了使子元件的高度能填滿整個頁面的高度,
所以設定如下。
section.outside 的高度,可以正常填滿整個頁面。
但是 .inside 卻無法,它只會維持在自己高度,height:100% 沒有作用。
這是為什麼?
/images/emoticon/emoticon19.gif

<section>
  <h2></h2>
  <div class="outside">
    <div class="inside">a</div>
  </div>
</section>
section{
    display:flex;
    flex-direction: column;
    min-height: 100vh;
}
.outside{
    width:100%;
    flex: 1 1 0%;
    padding: 20px;
}
.inside{
    width:100%;
    height:100%;
}
.inside 的 height: 100% 會試圖繼承「父層 .outside 的高度」。

但 .outside 並沒有明確高度,它的高度非固定數值或 % 計算來的。

所以,.inside 沒有一個可以「計算的明確高度」,導致 height: 100% 無效。
section {
display: flex;
flex-direction: column;
height: 100vh; /* 明確設定高度 */
}

.outside {
height: 100%; /* 繼承 section 高度 */
padding: 20px;
box-sizing: border-box; /* 確保 padding 不超出範圍 */
}

.inside {
height: 100%; /* 現在有效了 */
}
若 .inside 是唯一子元素,也可以直接使用 flex 撐滿它:

.outside {
display: flex;
flex-direction: column;
flex: 1 1 0%;
padding: 20px;
}

.inside {
flex: 1; /* 撐滿 .outside */
}
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

2 個回答

1
文科少女
iT邦新手 3 級 ‧ 2023-12-20 20:42:37
最佳解答

這是因為你並沒有設定明確的高度,只有寫min-height: 100vh;
再來outside會有高度是因為你下了flex: 1,當有剩下的空間,flex item就會自己變高,可是實際上它並沒有被套用高度,inside也就一樣吃不到高度。

0
咖咖拉
iT邦好手 1 級 ‧ 2023-12-15 13:51:41
section {
  height: 100vh;
}

比較簡單的方式

我要發表回答

立即登入回答