Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

still have space after margin, padding, border all zero?

I have set margin, padding, and border to zero, yet there is still space around my canvases and divs in both Firefox and Chrome. Clearly, I do not understand how to snug up elements in HTML, and would be grateful for advice & pointers.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>Spacing Question</title>
<style type="text/css">
    *
    {
        border: 0px;
        margin: 0px;
        padding: 0px;
    }
    canvas
    {
        width: 150px;
        height: 150px;
    }
    body
    {
        background-color: Purple;
        color: Silver;
    }
</style>
<script>
    function draw() {
        var canvas = document.getElementById('canvas1');
        if (canvas.getContext) {
            var ctx = canvas.getContext('2d');
            ctx.fillStyle = "rgb(200, 0, 0)";
            ctx.fillRect(0, 0, 150, 150);
        }
        canvas = document.getElementById('canvas2');
        if (canvas.getContext) {
            var ctx = canvas.getContext('2d');
            ctx.fillStyle = "rgb(0, 200, 0)";
            ctx.fillRect(0, 0, 150, 150);
        }
    }
</script>
</head>
<body onload="draw()">
<canvas id="canvas1" width="150" height="150">
    Fallback content 1.
</canvas>
<canvas id="canvas2" width="150" height="150">
    Fallback content 2. 
</canvas>
<div id="allYourControls">
</div>
</body>
</html>
like image 618
Reb.Cabin Avatar asked Nov 29 '22 03:11

Reb.Cabin


2 Answers

It's the whitespace (in this case, a line break) between your two <canvas>:

..
</canvas>
<canvas id="canvas2" ..

If you change it to this, the gap will be gone:

</canvas><canvas id="canvas2"

Alternatively, you can keep your whitespace, and add float: left to canvas in your CSS. If you choose to float them, you probably want to also add #allYourControls { clear: both } to clear your floats.

like image 115
thirtydot Avatar answered Nov 30 '22 18:11

thirtydot


  • The canvas element has a display of inline by default.
  • HTML collapses all multiple instances of whitespace into a single space.

These two properties combine in your case (and many others) to create a little gap between your elements. You have a line break between your canvases:

<canvas></canvas>
<canvas></canvas>

The browser thinks you're just trying to insert a bunch of spaces in between two inline elements. It thinks you're trying to do something like this:

<p>Best of all for man would be
to never exist, second best
would be to die soon.</p>

So it "collapses" those line breaks into a single space. It's the same reason that the above paragraph, for the most part, would be displayed as a single, normal line of text.

tl;dr Put your canvases on the same line.

As @thirtydot suggests, this is how to get rid of the gap:

<canvas>
    ...
</canvas><canvas>
    ...
</canvas>
like image 33
sdleihssirhc Avatar answered Nov 30 '22 18:11

sdleihssirhc