I need to Center a Div in the html viewport. It should be centered both, vertically and horizontally. But the Div should keep its aspect ratio (4/3) and have a minimum margin of 10px.
I made a Javascript:
function resizeWindow() {
var wHeight = $(document).height() - 20;
var wWidth = $(document).width() - 20;
var gameStage = $("#gameStage");
if ((wWidth / 4) * 3 <= wHeight) {
gameStage.css("width", wWidth + "px");
gameStage.css("height", ((wWidth / 4) * 3) + "px");
gameStage.css("top", (wHeight - ((wWidth / 4) * 3)) / 2 + 9 + "px");
gameStage.css("left", "10px");
} else {
gameStage.css("height", wHeight + "px");
gameStage.css("width", ((wHeight / 3) * 4) + "px");
gameStage.css("left", (wWidth - ((wHeight / 3) * 4)) / 2 + 9 + "px");
gameStage.css("top", "10px");
}
}
https://jsfiddle.net/3sw06kvb/
But User, who disabled Javascript will not be able to use my website. And a solution with HTML/CSS should be faster(?).
My first Idea is to make a wrapper with
position: fixed
top, left, bottom, right = 20px;.
But my problem is making a div centering vertically and horizontally while keeping its aspect ratio.