如何让HTML容器和嵌入其中的iframe,大小一模一样

How to make the HTML container and iframe embedded in it, exactly the same size

我用 P5.js web editor 创建了一个简单的草图,我想将其嵌入到我的网站中。 我的测试草图的 canvas 的高度和宽度均为 300px。 This is what the sketch looks light when I simply drop it on a website and this 是我添加一些简单的 CSS 后的样子。这是我的代码:

#container {
  border: 2px solid blue;
  display: inline-block
}


#canvas {
  width: 300px;
  height: 300px
}
 <div id="container">
      <iframe src="https://editor.p5js.org/Kubi/embed/BkuSPoiZ4" frameBorder="0" id="canvas"></iframe>
</div>

虽然我手动将 #canvas 元素的大小设置为 300 x 300px,但外部 #container 明显更大,高度为 304 像素。 为什么会这样?如何使 #container 与 iFrame 的大小完全相同,而无需手动设置 #container 的大小?

这是因为您在容器的每一侧设置了 2px 的边框:border: 2px solid blue; 这将容器扩展了 4px(左侧 2px,右侧 2px),因此宽度为 304px。您可以将 CSS 更改为以下内容以获得 300x300 像素的容器:

#container {
  display: inline-block;
  line-height: 0;
}

line-height 删除了所有元素底部的 space 以最小化行之间的 space。