Search code examples
csscss-positionabsolute

How to place a button relative to an absolute positioned element


PROBLEM

  • Can't place the Save and Reset button beneath the canvas.

  • You can took a look at the example below. But my canvas has absolute position so I can not use it as a reference to place button beneath.

MINIMAL REPRODUCIBLE EXAMPLE

HTML

<html>

  <head>
    <meta charset="UTF-8" />
    <link href="style.css" rel="stylesheet" />
    <title>Drawing Canvas</title>
  </head>

  <body>
    <h1 class="title">Simple Drawing</h1>
    <p class="title">Click and drag your mouse to draw on the canvas.</p>
    <canvas id="canvas"></canvas>
    <button>Save</button><button>Reset</button>
    <script src="canvas.js"></script>
  </body>

</html>

CSS

#canvas {
  position: absolute;
  border: 2px solid black;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%)
}

.title {
  text-align: center;
}

Solution

  • Recommendation: avoid position: absolute for the canvas elements

    If it's only to center the canvas, you might not need position: absolute; for it. In the snippet below:

    • Eliminated canvas.width = ... statement, and used CSS to set the width instead.
    • Removed position: absolute; from #canvas, and used display: block; and margin: 0 auto; to horizontally center it
    • Added a separate .buttons container for optional styling for buttons.

    If vertical centering of canvas is a critical requirement, you can still use other CSS layout techniques without absolute positioning.

    window.addEventListener('load', () => {
      // Get canvas //
      const canvas = document.getElementById("canvas")
      // Set canvas context for 2D //
      const ctx = canvas.getContext("2d")
    
      // Modify Canvas size //
      canvas.height = window.innerHeight / 2
    })
    #canvas {
      border: 2px solid black;
      margin: 0 auto;
      width: 50%;
      display: block;
    }
    
    .title {
      text-align: center;
    }
    
    .buttons {
      text-align: center;
    }
    <h1 class="title">Simple Drawing</h1>
    <p class="title">Click and drag your mouse to draw on the canvas.</p>
    <canvas id="canvas"></canvas>
    <div class="buttons">
      <button>Save</button><button>Reset</button>
    </div>