1

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.

Hashem Qolami
  • 97,268
  • 26
  • 150
  • 164
user3412531
  • 27
  • 1
  • 6
  • possible duplicate of [How to center a div in a div - horizontally?](http://stackoverflow.com/questions/114543/how-to-center-a-div-in-a-div-horizontally) – Stratus3D Mar 12 '14 at 20:34

2 Answers2

5

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 or width of the initial containing block is changed, they are scaled accordingly.

vh unit
Equal to 1% of the height 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;
}

WORKING DEMO.

It's worth noting that vh, vw viewport-percentage lengths are supported in IE9+.


Browser compatibility

enter image description here

Credits: Mozilla Developer Network

Hashem Qolami
  • 97,268
  • 26
  • 150
  • 164
1

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>
Honbra
  • 23
  • 6