Why am I getting overflow when i mentioned width to be window.innerwidth and height to be window.innerheight

Viewed 49

screenshot for reference

So I have been wondering what is causing the overflow to happen when I mention height and width to be window.innerheight and window.innerwidth respectively.

Here's a snippet:

var canvas = document.querySelector('canvas');

canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
* {
  box-sizing: border-box;
}

html,
body {
  margin: 0;
  padding: 0;
}

canvas {
  border: 1px solid;
}
<body>
  <canvas id="canvas" width=""></canvas>

  <script src="./canvas.js"></script>
</body>

2 Answers

Set the width and height in css by using:

canvas {
    width: 100%;
    height: 100%;
}

The short answer seems to be that width and height are HTML attributes - nothing to do with CSS - whereas box-sizing is to do with CSS. i.e. the box-sizing is not affecting the width/height + border settings so you get overflow.

For the longer answer I tried to understand what was happening on my Windows10 system (Edge/Chrome) when setting the canvas dimensions by CSS, leaving the attributes untouched. I only partially understand, the x direction seemed fine, the border was there but the vertical border on the right was hidden bizy a vertical scroll bar - it seemed as though the calculation was one pixel out until I went full screen at which point there was no scrolling.

Hopefully someone else can explain in more depth what is happening here as the box-sizing on the canvas seemed to work but not to the full extent.

This snippet sets everything to have margin and padding 0 just to be on the safe side.

canvas = document.querySelector('canvas');

function resize() {
  //canvas.width = window.innerWidth;
  //canvas.height = window.innerHeight;
  canvas.style.width = window.innerWidth + 'px';
  canvas.style.height = window.innerHeight + 'px';
}
window.onresize = resize;
resize();
* {
  box-sizing: border-box;
}

* {
  margin: 0;
  padding: 0;
}

canvas {
  border: 10px solid;
}
<canvas id="canvas" width=""></canvas>

Related