Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Center Div with aspect Ratio

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/


1 Answers

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>
like image 199
Sooraj Avatar answered Nov 20 '25 19:11

Sooraj



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!