Reputation: 27
I want to keep the .center
div's width relative to its height by 4:3
aspect ratio (4 width per 3 height) and height of 100%
; Then align center the div horizontally.
Like you can see here with a flash application.
This is what I have:
HTML:
<div id="stuff" class="center" width="800" height="600">
<canvas id="someHTML5">You cant play HTML5</canvas>
</div>
CSS:
.center {
position: absolute;
left: 50%;
width: 800px; /* how do I make this relative; i want: pseudo code: width: height/3*4; */
height: 100%;
margin-left: -400px; /* -width/2 for horizontal alignment */
z-index: 100;
}
I have also a JavaScript loop to integrate JavaScript side updates.
Upvotes: 1
Views: 2981
Reputation: 23
I made a script that resizes like a video.
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: 99564
Since the width
of the box should be changed relative to its height
, you could use vh
viewport relative length as the value of the width
property.
From the Spec:
The viewport-percentage lengths are relative to the size of the initial containing block. When the
height
orwidth
of the initial containing block is changed, they are scaled accordingly.vh unit
Equal to1%
of theheight
of the initial containing block.
Here you go:
.center {
position: absolute;
left: 50%;
width: 133.33vh; /* 100 * 4/3 ratio */
height: 100%;
margin-left: -66.66vh; /* width / 2 */
z-index: 100;
}
It's worth noting that vh
, vw
viewport-percentage lengths are supported in IE9+.
Credits: Mozilla Developer Network
Upvotes: 5