user2706510
user2706510

Reputation: 141

Absolute position together with a canvas

I have a question why a span is positioned at the bottom of the root span. I created a plunker:

/* Styles go here */

span {
  background-color :#808080;
}

canvas {
  background-color:#800000;
}
<!DOCTYPE html>
<html>

  <head>
    <link rel="stylesheet" href="style.css">
    <script src="script.js"></script>
  </head>

  <body>
    <span style="position:relative">
      <canvas width="100" height="100">
      </canvas>
      <span style="position:absolute; left:0px; top:0px;">after</span>
    </span>
  </body>

</html>

I expected the "after" String at the top of the dark-red area, not at the bottom. Why: The outer span defines position:relative, so this is the anchor for childs with position:absolute.

The inner span with position:absolute and top=0px,left=0px; should be positioned at the upper left corner of the outer span.

The outer span doesn't enclose the canvas, this is another point I dont understand.

Can anyone tell me why the outer span doesn't enclose the canvas. I think this is the reason why the inner span is not positioned at the opper left border of the red rectangle.

Upvotes: 0

Views: 3110

Answers (2)

Dariusz Sikorski
Dariusz Sikorski

Reputation: 4407

It's because you put block element (canvas) inside inline element (span). As result Span element does not stretch to it's block content. To prevent this add display: inline-block to your span element.

Ps. While it will work now - nesting block-level elements inside inline is not w3c valid, so I'd suggest to replace span with div.

Another suggestion - when you set values to 0, don't add units, in your case use left: 0; top: 0; instead of left: 0px; top: 0px;

Fixed example: https://plnkr.co/edit/MAfzT9A3uJwHAN8YtpKF?p=preview

Upvotes: 1

Gabriele Petrioli
Gabriele Petrioli

Reputation: 195972

This happens because the canvas is inside a span which is display:inline so it (the span) is not resized by the size of the canvas. (the canvas overflows the span*)

To showcase the problem see

/* Styles go here */

span {
  background-color :#808080;
  border:1px solid black;
}

canvas {
  background-color:rgba(100,0,0,0.5);
}
<span style="position:relative;">
      <canvas width="100" height="100">
      </canvas>
      <span style="position:absolute; left:0px; top:0px;">after</span>
    </span>

Setting the outer span to display:inline-block will fix the problem.

See

/* Styles go here */

span {
  background-color :#808080;
  border:1px solid black;
}

canvas {
  background-color:rgba(100,0,0,0.5);
  display:block;
}
<span style="position:relative;display:inline-block;">
      <canvas width="100" height="100">
      </canvas>
      <span style="position:absolute; left:0px; top:0px;">after</span>
    </span>

Upvotes: 2

Related Questions