Frank
Frank

Reputation: 2230

Is it possible to relatively position an element OVER a relatively positioned canvas?

Here is my problem:

I have a canvas element that I center in the documentElement using JavaScript. It has a relative position so that it can still flow nicely with the p elements above and below it. I would like to put another p element on top of the canvas. Right now I'm doing it like this:

var element=document.getElementById("my_canvas_element");

while(element.parentElement){
    offset_x+=element.offsetLeft;
    offset_y+=element.offsetTop;
    element=element.parentElement;
}

my_p_element.style.left=offset_x+"px";
my_p_element.style.top=offset_y+"px";

This will accurately position my_p_element at the top left corner of the canvas element as long as I set my_p_element's CSS position to absolute. Is there any way to position my_p_element in the top left corner of my relatively positioned canvas element using only CSS?

That is, is there a way to place a p element in the top left corner of a relatively positioned canvas using only CSS?

Thanks!

Upvotes: 0

Views: 793

Answers (1)

markE
markE

Reputation: 105035

How about wrapping your canvas and paragraph elements in a div with that div position:relative.

Then you can position:absolute the canvas and paragraphs as needed relative to the parent div.

enter image description here

body{ background-color: ivory; padding:0px;}
#wrapper{position:relative; border:1px solid blue; width:300px; height:300px; }
#p1{position:absolute; top:-15px; border:1px solid green;}
#canvas{position:absolute; border:1px solid red;}
<div id=wrapper>
  <p id=p1>I'm a top-left paragraph element</p>
  <canvas id="canvas" width=300 height=300></canvas>
</div>

Upvotes: 1

Related Questions