Setting element height to clientHeight cause page scroll

Viewed 609

I have this piece of code:

<!DOCTYPE html>
<html lang="en">
  <head>
    <script>      
        window.addEventListener('load', () => {
            document.getElementById("c").width = document.documentElement.clientWidth;
            document.getElementById("c").height = document.documentElement.clientHeight;
        })
    </script>
  </head>
  <body style="margin: 0;">
    <canvas id="c" style="background-color: red;"></canvas>
  </body>
</html>

Why it generates canvas bigger than browser viewport, and makes scrollbar? And beside that it makes some white space below canvas. Why and how to solve it? Thanks!

1 Answers

By default canvas display are set to display: inline;
You just have to set your canvas display to display: block;

<!DOCTYPE html>
<html lang="en">
  <head>
    <script>      
        window.addEventListener('load', () => {
            document.getElementById("c").width = document.documentElement.clientWidth;
            document.getElementById("c").height = document.documentElement.clientHeight;
        })
    </script>
  </head>
  <body style="margin: 0;">
    <canvas id="c" style="background-color: red; display: block;"></canvas>
  </body>
</html>

Related