iframe 的應用很普遍,需求大致有兩種:一是想做出帶捲軸的獨立區塊,節省版面;二是想嵌入另一個頁面,形成框架式連結。
如果不方便使用 iframe,可以這樣替代:第一種需求直接用 CSS 版面就能完成,既少一個檔案,效率也更高;第二種需求則可用 XMLHttpRequest 遠端抓取內容後填入容器。
以下提供四種以 CSS 模擬的實作方式。
最直白的做法,靠 overflow: auto 產生捲軸:
#content {
overflow: auto;
height: 200px;
width: 600px;
background: #f00;
}
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>用 CSS 構建 iframe 效果</title>
<style>
* { font: 12px Arial; }
html { overflow: hidden; border: 0; height: 100%; }
body { overflow: hidden; height: 100%; }
#content {
overflow: auto;
height: 185px;
width: 600px;
background: #ccc;
padding: 10px;
}
</style>
</head>
<body>
<h4 style="font-weight:bold;">用 CSS 構建 iframe 效果</h4>
<p>A. 直接模擬 iframe,用層做容器</p>
<div id="content">
<p>這裡放內容,超出高度時會自動出現捲軸。</p>
</div>
</body>
</html>
html {
overflow: hidden;
height: 100%;
background: #fff;
border: 0;
}
* html { padding: 100px 0 0 100px; }
body {
overflow: scroll;
background: #f00;
margin: 0;
position: absolute;
top: 100px;
left: 100px;
bottom: 0;
right: 0;
}
* html body { height: 100%; width: 100%; }
這種做法讓 body 本身變成可捲動的區塊,再用絕對定位把它限制在頁面的某個範圍內。好處是不必多一層標記;代價是整頁只剩下這個區域能捲動,其他內容得另外安排。
html {
overflow: hidden;
border: 0;
height: 100%;
max-height: 100%;
}
body {
overflow: hidden;
margin: 0;
height: 100%;
max-height: 100%;
position: relative;
}
#head {
position: absolute;
top: 0;
right: 15px;
width: 100%;
height: 100px;
background: #f00;
z-index: 2;
}
#foot {
position: absolute;
bottom: 0;
right: 15px;
width: 100%;
height: 50px;
background: #f00;
z-index: 2;
}
#content {
height: 100%;
position: relative;
z-index: 1;
overflow: auto;
}
頁頭與頁腳以絕對定位固定在上下兩端,中間的內容層佔滿整個高度並自行捲動。right 留出的 15px 是為了避開右側的捲軸。這個結構就是早期「固定頁首頁腳、中間捲動」的經典寫法。
html {
height: 100%;
max-height: 100%;
border: 0;
overflow: hidden;
}
* html { padding: 100px 0 50px 0; }
body {
height: 100%;
max-height: 100%;
margin: 0;
overflow: hidden;
}
#content {
position: absolute;
top: 100px;
bottom: 50px;
left: 0;
right: 0;
z-index: 3;
width: 100%;
overflow: auto;
}
* html #content { top: 100px; bottom: 0; height: 100%; }
#head {
position: absolute;
margin: 0;
top: 0;
left: 0;
width: 100%;
height: 100px;
background: #f00;
z-index: 5;
}
#foot {
position: absolute;
margin: 0;
bottom: 0;
left: 0;
width: 100%;
height: 50px;
z-index: 5;
background: #f00;
}
與 B-1 的差別在於捲軸的位置:這裡捲軸被限制在中間的內容層內部,頁首頁腳不會隨捲軸移動,視覺上更像獨立的框架。原文以 IE 6.0 與 Firefox 1.5 測試通過。
這幾種寫法示範了「用 overflow 與絕對定位拼出可捲動區域」的思路,在需要避開 iframe 時很有參考價值。不過若目標是現代瀏覽器,用 Grid 或 Flexbox 加上 min-height: 0 來處理捲動容器,程式碼會短得多;固定頁首頁腳的效果也可以直接用 position: sticky 完成,不必再靠絕對定位堆疊。