Search code examples
javascripthtmlcss

Width 50% and Margin 0 px not aligning


Im building a 3D render for JavaScript and the first feature I need is a X , Y mouse display. This display is a paragraph tag which is in a div which should be aligned. right next to each other.

I've tried changing the div width, margin, padding, float, align but it just doesn't seem to work.

let renArea = document.querySelector("#render");
let cc = renArea.getContext("2d"); //cc for canvas contenxt.

//Pre-Display
document.querySelector("#postion-display").innerHTML = "Put mouse on canvas.";

//Get mouse (X, Y) and siplay it for user refrence. 
function getMousePosition(canvas, event) {
    let rect = canvas.getBoundingClientRect();
    let x = event.clientX - rect.left;
    let y = event.clientY - rect.top;
    document.querySelector("#postion-display").innerHTML = "Coordinate x: " + Math.round(x) + " Coordinate y: " + Math.round(y);
}

renArea.addEventListener("mousemove", function (e) {
    getMousePosition(renArea, e);
}); 


cc.moveTo(0, 0);
cc.lineTo(200, 100);
cc.stroke();
html, body {
    margin: 0px;
    margin-top: 5vh;
}

.wrapper {
    margin: 0px;
}

.header {
    position: fixed;
    padding: 1px;
    width: 100%;
    top: 0;    
    padding-left: 12px;
    background: lightcoral;
}

.render-area {
    margin: 0px;
}

canvas {
    border: 2px solid black;
    float: right;
    margin-right: 10px;
}
<!DOCTYPE html>
    <html>
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Render | Js</title>

        <link rel="stylesheet" href="media/global.css">
    </head>
    <body>
        <div class="wrapper">
            <div class="header">
                <h3>Render | Js</h3>
            </div>

            <div class="editor" style="width: 50%; float: left;">
                <p id="postion-display"></p>
            </div>
            <div class="render-area" style="float: left; width: 50%;">
                <canvas width="500" height="500" id="render"></canvas>
            </div>
        </div>

        <script src="./src/render.js"></script>
    </body>
</html>


Solution

  • It depends on how you define aligned, but the best approach is to place the two elements inside a display: flex container, thus enabling you to justify and align them in many ways. See also https://css-tricks.com/snippets/css/a-guide-to-flexbox/

    .d-flex {
      display: flex;
      width: 100%;
      
      /* the X axis */
      justify-content: center;
      
      /* the Y axis */
      align-items: start;
    }
    
    
    /* remove margin of <p> */
    #postion-display {
      margin: 0;
    }
    <div class="d-flex">
    
      <div class="editor">
        <p id="postion-display">X: 200, Y: 300</p>
      </div>
      
      <div class="render-area">
        <canvas width="200" height="200" id="render" style="border: 1px solid red"></canvas>
      </div>
      
    </div>