當flexbox遇到height: 100%

狗狗
狗狗
Nov 6 · 4 min read

今天想來聊聊當前最方便最火紅的網頁排版方式之一:flexbox

前陣子在專案上遇到滿有趣的問題,花了點時間去解決所以做個紀錄,以下是日常開發中常常遇到的排版方式:

其中要符合幾個需求:

  1. 無論screen size多大,MenuBar及Header必須在頁面最上方,Footer必須在頁面最下方。
  2. Content區塊無論內容多寡,高度需撐開至最高。

根據以上需求,我們很常使用flexbox做以下的排版:

## CSS

body, html {
margin: 0;
padding: 0;
}
.container {
height: 100vh;
display: flex;
flex-flow: column;
}
.content {
flex-grow: 1;
}
.inner-content {
height: 100%;
}

## HTML

<div class="container">
<div class="content">
<div class="inner-content">
Main content
</div>
</div>
<div class="footer">
Footer
</div>
</div>

如以下範例:

但是當這樣的排版方式被放在各個browser上去做檢視,有趣的事情就發生了,以下是Chrom跟Firefox上的表現,而這樣的排版結果如同我們預期:

但是在Safari上看到的卻是:

找了一些資料後發現這是Safari在flexbox的處理上的known issue,在nested flexbox上設置height: 100%時,高度會無法被正確的撐開至最高,原先在Chrome上也有一樣的bug但之後解掉了,只剩下Safari上有這樣的問題。

Solution

既然這種情況之下Safari看不懂height: 100%,那麼我們就用其他方式去解決吧!以下是用position去取代了height: 100%的做法:

.container {
height: 100vh;
display: flex;
flex-flow: column;
}
.content {
flex-grow: 1;
position: relative; // Add this to replace height: 100%
}
.inner-content {
position: absolute; // Add this to replace height: 100%
top: 0; // Add this to replace height: 100%
bottom: 0; // Add this to replace height: 100%
left: 0; // Add this to replace height: 100%
right: 0; // Add this to replace height: 100%
}

於是我們的排版就回來啦!以上做法在各個browser上都檢視過一輪,呈現效果皆如原先預期。

狗狗

Written by

狗狗

前端工程師 | 對前端開發充滿熱情,在前端打滾了六年,決定開始將開發時遇到的問題及踩到的雷記錄下來,擅長網頁跨platform及browser的問題處理

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade