如何将四个iframe按1|2、3|4的布局排列?附现有代码
解决iframe两行两列并排布局问题
没问题,我来帮你搞定这个布局需求!你想要实现两行各两个iframe并排展示,当前代码的核心问题是没有给承载iframe的.box容器设置合适宽度,导致iframe的width:100%会把容器撑满,没法实现并排效果。下面是调整后的完整代码,以及关键修改点说明:
关键调整点
- 给
.box容器设置宽度:使用width: calc(50% - 10px),这样两个容器加起来刚好占满一行(减去的10px是为了抵消右边距的一半,避免总宽度超出父容器) - 保留
.clear类清除浮动,确保第三、第四个iframe能换到新的一行 - 给body添加少量内边距,避免内容紧贴浏览器边缘
- 用
nth-child选择器移除每行第二个元素的右边距,避免行尾出现多余空隙
修改后的完整代码
<!doctype html> <html> <head> <style type="text/css"> .box { float: left; width: calc(50% - 10px); /* 核心:设置容器宽度,让两个能并排 */ margin-right: 20px; margin-bottom: 20px; /* 可选:给行之间添加间距 */ box-sizing: border-box; /* 确保内边距/边框不会增加总宽度 */ } /* 清除每行第二个元素的右边距 */ .box:nth-child(2n) { margin-right: 0; } .clear { clear: both; } body { padding: 20px; /* 可选:让内容不贴边 */ margin: 0; } iframe { width: 100%; height: 512px; border: 0; scrolling: no; } </style> </head> <body> <div class="box"> <iframe src="webgl_sphereWithEquator.html"></iframe> </div> <div class="box"> <iframe src="webgl_hopftorus1.html"></iframe> </div> <div class="clear"></div> <!-- 清除浮动,强制换行 --> <div class="box"> <iframe src="你的第三个iframe地址.html"></iframe> </div> <div class="box"> <iframe src="你的第四个iframe地址.html"></iframe> </div> </body> </html>
额外说明
- 如果你的iframe需要固定宽度(比如600px),可以把
.box的width改成固定值,只要两个容器的总宽度不超过父容器即可 box-sizing: border-box是为了后续给.box加边框或内边距时,不会破坏现有的宽度布局
内容的提问来源于stack exchange,提问作者Stéphane Laurent
相关产品推荐
相关产品推荐

