I have a div and I want to overlay a canvas exactly on top of it with the same width, height, padding and margins. Although I am using position: absolute like most questions here recommend and z-index the canvas is still showing underneath the div. This is the code I have until now.
<div id ="editor-section">
<div class="editable" id="editor"></div>
</div>
// the canvas is created / removed dynamically on connection / disconection
hub.client.broadcastSomeoneConnected = function (connectionId, someoneConnected)
{
if (someoneConnected) {
var canvas = document.createElement("canvas");
canvas.id = connectionId;
canvas.className = 'canvases';
canvas.style.border = '2px solid red';
canvas.style.zIndex = zindex;
zindex++;
var parentDiv = document.getElementById("editor-section");
parentDiv.appendChild(canvas);
} else { // someone disconnected
var canvas = document.getElementById(connectionId);
canvas.parentNode.removeChild(canvas);
}
}
// css for all canvases
.canvases {
width:60%;
height:700px;
border:1px solid;
position:absolute;
padding: 5%;
margin-left:20px;
pointer-events: none;
}
// css for editor div
#editor {
padding: 5%;
margin-left:20px;
border: 2px solid black;
overflow-y:scroll;
height: "700px";
width: "100%";
background-color: white;
margin-bottom:30px;
}
PS: zindex is initialized globally because I need multiple canvases layered on top of each other and the editor eventually depending on the number of people connected
What am I doing wrong here? Thanks
We wrap the canvas and div in a container element, which is position: relative . Then the canvas and div are set to position: absolute . This is a great answer... but... When I have a large <div> the canvas element bleeds right thru the div, no matter what the z-index, the background color or background-image?
First, I made the canvas' position absolute so it exists outside of the normal document flow. Next, I set the canvas' z-index to 2 so it's "on top" of the DOM. Finally, I set the pointer-events style to "none" so the canvas doesn't block the DOM from handling pointer events (e.g. click, hover, etc.)
You cannot place elements inside a canvas (and have both displayed); they are only displayed if the browser does not understand the canvas element.
Use z-index and top . This will layer the div on bottom, the image and then the span (overlay) on top. To set the positioning from the top edge, use top , which can be used with negative numbers if you need it to be higher on the Y axis than it's parent.
Almost there. Move width and height on the container, make it relative, and the editor and canvas absolutely positioned at 0,0 with 100% width/height. The zIndex
of your editor must be lower than the zIndex
of your canvas. fiddle
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With