如何仅用CSS在更大的iframe中垂直居中iframe的src内容?
如何在iframe尺寸大于其src内容时,垂直对齐src内容?
需求:将1000×1000的紫色方块(src内容)居中在1100×1100带红色边框的iframe中,优先使用CSS实现,必要时可借助JS。
已尝试flex布局、display: table;、position: relative、响应式iframe等方法,但均无效。
代码示例
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Test…</title> <style> /* Styles for this page... */ body { margin: 1%; padding: 1%; display: flex; flex-direction: column; justify-content: center; align-items: center; border: thin solid blue; } main { /* Like Google sites window. */ width: 1175px; height: 1175px; display: flex; justify-content: center; align-items: center; border: thin solid green; } footer { text-align: center; font-size: x-small; } /* Styles for included code... */ div { overflow: hidden; } iframe { /* Flex Box style does nothing for the iframe src. */ display: flex; flex-direction: column; justify-content: center; align-items: center; min-width: 1100px; min-height: 1100px; border: thin solid red; } </style> </head> <body> <main> <!-- HOW TO VERTICAL-ALIGN CENTER THE IFRAME SRC IN THE IFRAME? --> <div> <iframe src="https://psb-david-petty.github.io/p5js/2023-2024-bhs-schedule/whatever.html"></iframe> </div> </main> <footer> <!-- Explanatory footer... --> <p> <code><body></code> <span style="color: blue;">blue</span> border — <code><main></code> 1175x1175 (like a Google sites embed) <span style="color: green;">green</span> border — <code><iframe></code> 1100x1100 <span style="color: red;">red</span> border </p> </footer> </body> </html>
编辑:明确标题,修正1100×1100尺寸。
解决方案
1. 可控制src页面内容时(最优方案)
直接在iframe指向的页面中,给<body>或最外层容器添加居中样式,让内容自身在视口中居中:
/* src页面的CSS */ body { margin: 0; min-height: 100vh; /* flex布局实现水平垂直居中 */ display: flex; justify-content: center; align-items: center; } /* 或者用更简洁的grid布局 */ body { margin: 0; min-height: 100vh; display: grid; place-items: center; }
这样不管iframe的尺寸多大,src内容都会自动居中。
2. 无法控制src页面内容时
CSS方案
给iframe的父容器设置相对定位,iframe用绝对定位配合transform实现居中:
div { position: relative; width: 1100px; height: 1100px; overflow: hidden; } iframe { position: absolute; top: 50%; left: 50%; /* 偏移自身50%实现真正居中 */ transform: translate(-50%, -50%); min-width: 1100px; min-height: 1100px; border: thin solid red; }
JS方案
如果CSS方法无效,可通过JS动态计算偏移量:
window.addEventListener('load', () => { const iframe = document.querySelector('iframe'); const container = iframe.parentElement; iframe.onload = () => { // 获取内容高度和容器高度 const contentHeight = iframe.contentWindow.document.body.scrollHeight; const containerHeight = container.offsetHeight; // 计算顶部偏移量 const topOffset = (containerHeight - contentHeight) / 2; // 设置margin-top实现垂直居中 iframe.style.marginTop = `${topOffset}px`; }; });
内容的提问来源于stack exchange,提问作者psb_david_petty
相关产品推荐
相关产品推荐

