【问题标题】:Remove extra space under canvas when it's width/height set to same as outer div's当画布的宽度/高度设置为与外部 div 相同时,删除画布下的额外空间
【发布时间】:2022-06-28 06:16:13
【问题描述】:

我有一个canvas,它的高度和宽度必须与它的父级div 完全相同。但是当包含div 有一个设置的宽度但没有一个高度时,画布下方会有额外的空间。我怎样才能摆脱它?

let div = document.querySelector("div");
let canvas = document.querySelector("canvas");
canvas.width = div.clientWidth;
canvas.height = div.clientHeight;
div {
  background: red;
  width: 100%;
}

canvas {
  background: grey;
}
<div>
  <canvas></canvas>
</div>

【问题讨论】:

    标签: html css


    【解决方案1】:

    最简单的解决方案是在父div上使用line-height: 0;

    let div = document.querySelector("div");
    let canvas = document.querySelector("canvas");
    canvas.width = div.clientWidth;
    canvas.height = div.clientHeight;
    div {
      background: red;
      line-height: 0;
      width: 100%;
    }
    
    canvas {
      background: grey;
    }
    <div>
      <canvas></canvas>
    </div>

    可以在此处找到有关原因和其他解决方案的更多详细信息: Image inside div has extra space below the image

    【讨论】:

      猜你喜欢
      • 2011-06-14
      • 2014-01-09
      • 1970-01-01
      • 1970-01-01
      • 2020-08-30
      • 1970-01-01
      • 2012-08-12
      • 1970-01-01
      • 2014-06-15
      相关资源
      最近更新 更多