0
votes

I wonder if I can set div ratio responsive like an image in css. For example, I have an image (800px x 400px) and set css is width:100%. When I use desktop screen (widht: 1400px), the image will auto resize and get full width of screen => image size (1400px x 700px). But element, I have to set both width and height Is there way to set empty width 800px and height 400px, and it will auto resize depends on the screen size, and it still keep ratio like an image.

Thank you

1

1 Answers

0
votes

If your browser support allows you, you may use viewport units to convey aspect ratio for the div. The rest will be handled by the browser.

You may define class names for different sizes. The one that will work for 16:9 images is:

width: 100vw;
height: 77.78vw;

16 / 9 => 1.777777777777778; In this case for 100% width of the viewport you need 77.78% height of the viewport applied to the element.

You can pre-define classes for different aspect ratios or use some simple JS to calculate this.

Codepen (same as below): https://codepen.io/Mchaov/pen/vJrgYa

html, body {
  height: 100%;
  margin: 0;
  padding: 0;
}

div {
  margin: 0;
  padding: 0;
  border: 1px solid red;
}

.autoScale-16-9 {
  width: 100vw;
  height: 77.78vw;
}
<div class="autoScale-16-9">auto scale div</div>