CSS positioning issue

140 Views Asked by At

I'm creating a game using melonJS. I would like to dynamically position dialog boxes over the NPCs.

In full screen, it looks fine.

enter image description here

When I shrink the viewport, the positioning stays absolute and therefore looks bad. But if I don't position absolute, I won't be able to place it relative to the NPC's coordinates as such:

$("#dialogBox").css({top: game.data.currentNPC_y+50, left: game.data.currentNPC_x-50, position:'absolute'});

enter image description here

Any way around this?


Edit:

When I use the following, the code doesn't scale as mentioned above, but at least it's still near the NPC and on the canvas:

        $("#dialogBox").css({
            top: game.data.currNPC_y+50, 
            left: game.data.currNPC_x-50, 
            position:'absolute'
        }); 

enter image description here

When I use the code you suggested, it appears outside the canvas:

        $("#dialogBox").css({
            position : "absolute",
            left     : (game.data.currentNPC_x - 50) * me.sys.scale.x,
            top      : (game.data.currentNPC_y - 500) * me.sys.scale.y
        });

enter image description here

1

There are 1 best solutions below

1
Jason Oster On

Scale the DOM absolute left by me.sys.scale.x and absolute top by me.sys.scale.y:

$("#dialogBox").css({
    "position" : "absolute",
    "left"     : (game.data.currentNPC_x - 50) * me.sys.scale.x,
    "top"      : (game.data.currentNPC_y + 50) * me.sys.scale.y
});

You can scale the element's width and height as well to better integrate.

Finally, you should listen to the WINDOW_ONRESIZE event to rescale the element dynamically as the user changes the window size, or mobile device orientation, etc.