CSS实现iframe占据页面剩余高度(无需JavaScript)
纯CSS实现iframe占据页面剩余高度
我创建了一个包含header、main区域及iframe的页面,iframe引用外部链接(页面布局示意图:
)。希望仅通过CSS而非JavaScript实现该iframe占据页面剩余高度,而非仅设置min-height。
当前页面body代码如下:
<body> <header> <div class="header-titles"> <div class="site-logo faux-heading"> <a href="https://www.psdgratuit.com/" class="custom-logo-link" rel="home"></a> </div> </div> </header> <main> <h1>{{title}}</h1> <h2>Download in progress</h2> <p> Your download strat automaticlly in few seconds <span class="blink_me">..</span> if it doesn't. <a href="{{file}}" id="downloadLink" download class="blink_me display-none">Please click here to strat it manually</a> </p> </main> <!-- I want this iframe take the rest of hieght--> <iframe src="https://unynow.com/blog/2023/03/01/zero-calorie-sweetener-linked-to-heart-attack-and-stroke-risk/" width="100%" style="min-height: 500px;" frameborder="0" ></iframe> </body>
目前仅为iframe设置了min-height:500px,但这只是最小高度,无法满足占据剩余高度的需求。
解决方案
方案一:Flexbox布局(推荐)
通过弹性布局让iframe自动填充剩余高度,兼容性好且实现简单:
/* 重置默认边距,确保body占满视口高度 */ body { margin: 0; min-height: 100vh; display: flex; flex-direction: column; } /* 让header和main保持自身内容高度,不被压缩 */ header, main { flex-shrink: 0; } /* 设置iframe占据剩余所有空间 */ iframe { flex: 1; width: 100%; border: 0; /* 可选:保留最小高度,避免内容过短时iframe过小 */ min-height: 500px; }
原理:body作为垂直方向的弹性容器,min-height:100vh确保至少铺满整个视口。header和main的flex-shrink:0防止它们被挤压,iframe的flex:1会自动分配容器剩余的所有空间。
方案二:Grid布局
用网格布局也能轻松实现,代码更简洁:
body { margin: 0; min-height: 100vh; display: grid; /* 前两行自适应内容高度,第三行占据剩余空间 */ grid-template-rows: auto auto 1fr; } iframe { width: 100%; border: 0; min-height: 500px; /* 可选最小高度 */ }
原理:grid-template-rows定义三行高度,auto表示跟随内容高度变化,1fr代表分配剩余的所有可用高度,直接让iframe占满剩余空间。
内容的提问来源于stack exchange,提问作者Nakous Mus
相关产品推荐
相关产品推荐

