Reputation:
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.
https://jsfiddle.net/xep2mf62/
Upvotes: 3
Views: 1088
Reputation: 23
Still JS, but simpler
window.onresize = function() {
resize();
};
function resize() {
var wrapper = document.querySelector(".wrapper");
var wrapperwidth = 1920;
var wrapperheight = 1080;
var vw = Math.max(document.documentElement.clientWidth, window.innerWidth || 0);
var vh = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);
var ratio = Math.min(vw / wrapperwidth, vh / wrapperheight);
wrapper.style.transform = `translate(-50%, -50%) scale(${ratio})`;
}
resize();
.wrapper {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 1919px;
height: 1079px;
overflow: hidden;
background-color: red;
}
/* demo text (smiley face) */
.wrapper::after {
content: ":)";
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
font-size: 200px;
font-family: "Roboto", 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}
<div class="wrapper"></div>
Upvotes: 1
Reputation: 10567
You can try the following in the CSS.
The new units in CSS3 vh
and vw
allows you to set the height depending on the size of the viewport. height:100vh
will give the element a height that is equal to the height of the browser window.
***1vw = 1% of viewport width
1vh = 1% of viewport height***
.wrapper {
position: relative;
width:100%;
height:100vh;
}
.childdivision {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
height:50vw;
width:90vw;
border:2px solid #444;
}
<div class="wrapper">
<div class="childdivision">
</div>
</div>
Upvotes: 2