Search code examples
htmlcssbuttoncanvasposition

Relatively positioning button over canvas cuts off majority of canvas


I am trying to make a game with JS, HTML, and CSS in which I use an HTML to open a bag/inventory menu. However, when trying to position my button to the bottom right of my game screen (canvas), a large portion of the canvas gets cut off, making it unplayable.

Here is what I see, and below it is my code.

screen

function setup() {

    game = new Game;
    player = new Player;
    controller = new Controller;
    canvas.width = 800;
    canvas.height = 600;

}
@font-face { font-family: "04b_03"; src: url("assets/fonts/04B_03__.TTF"); }

:root {

    --background: 15, 15, 15;
    --outline: 255, 160, 30;

}

html, body {

    /* Prevent scrollbars */
    overflow: hidden;

    /* Background */
    background-color: rgb(var(--background));

    /* Text */
    font-family: "04b_03", sans-serif;
    /* font-family: "Staatliches", cursive; */
    font-size: 200%;
    color: white;

}

.container {

    position: relative;
    width: auto;
    height: auto;

}

canvas {

    /* Center */
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);

    /* Border */
    border: 10px solid white;
    border-radius: 25px;
    box-shadow: 0 0 50px rgba(255, 255, 255, 0.4);

    /* Rendering */
    image-rendering: pixelated;

    /* Positioning */
    z-index: 1;

}

.bag {

    position: absolute;
    right: 5%;
    bottom: 5%;
    z-index: 2;

}
<body>

        FIRE

        <div class = "container">

                <canvas id = "canvas"> Your browser does not support the HTML canvas :( </canvas>

                <button class = "bag"> Bag </button>

        </div>

    </body>

How can I fix this? The container is being shrunk whenever I use the relative positioning, but I don't believe there is any other way to do it. Using the absolute positioning will create errors in the button position if the final end-user decides to zoom their screen, so I am trying to look for a solution in which the button will always stay in the same spot over the canvas.


Solution

  • Never mind, I got it to work. I used the fixed positioning on my container CSS. Here it is:

    .container {
    
        position: fixed;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
    
    }