Search code examples
javascriptcsscanvasposition

How to layer elements with CSS position property?


I've looked at all the questions on here asking the same thing and tried every suggestion, none of it is working for me.

I want to layer two dynamically created canvas elements on top of each other, inside the div with an id of "plotPlaceholder".

It continues to just show one below the other, like so:

enter image description here

// grab elements from form
var wid = document.getElementById("wid").value;
var hei = document.getElementById("hei").value;

// grab div container and create canvas elements
var canvasPlaceholder = document.getElementById("plotPlaceholder");
var baseCanvas = document.createElement("canvas");
var canvasElement = document.createElement("canvas");

canvasElement.width = wid;
canvasElement.height = hei;
baseCanvas.width = wid;
baseCanvas.height = hei;
baseCanvas.style.zIndex = "1";
canvasElement.style.zIndex = "2";
    
baseCanvas.id = "canvasToHoldGrid";
canvasElement.id = "plottingCanvas";
canvasPlaceholder.appendChild(baseCanvas);
canvasPlaceholder.appendChild(canvasElement);
canvas {
    border: 2px solid #27a3ea;
    position: absolute;
    top: 0;
    left: 0;
}

#plotPlaceholder {
    position: relative;
}
<div id="plotPlaceholder"></div>


Solution

  • I found out what was happening - there was an extra div being created (parent of the canvas elements) with a class of 'canvas-container'. The position property was being overwritten.

    .canvas-container {
        position: absolute !important;
        top: 0;
        left: 0;
    }
    

    That !important fixed it, although I'm sure it's not best practice in most circumstances.