0

I have a div I would like to mantain aspect ratio 2:1 no matter the screen size and ratio are.

This is my choice (discarding other previous options)

.mydiv{

    background-color: red;
    width: 100%;
    position: absolute;
    height: 50%;
}
<div class="mydiv">
    this should be a fixed aspect ratio div
  </div

I tried media queries and this: https://www.w3schools.com/howto/howto_css_aspect_ratio.asp but it is not what I'm looking for because of the white padding space

cucuru
  • 3,146
  • 5
  • 33
  • 66

3 Answers3

1

Set left and top property .mydiv to 0 and also set margin:0 to body to remove the extra space.

Stack Snippet

body {
  margin: 0;
}

.mydiv {
  background-color: red;
  width: 100%;
  position: absolute;
  height: 50%;
  left: 0;
  top: 0;
}
<div class="mydiv">this should be a fixed aspect ratio div
  </div

I hope this will help you!

Bhuwan
  • 16,080
  • 5
  • 30
  • 52
1

try this

.mydiv{

    background-color: red;
    width: 100vw;
    height: 50vh;
    position: absolute;
    left:0;
    right: 0;
    top: 0;
    bottom: 0;
}
<div class="mydiv">
    this should be a fixed aspect ratio div
  </div
satyajit rout
  • 1,596
  • 9
  • 19
0

You can use padding-bottom and choose the percentage according to your desired ratio

.mydiv{
    background-color: red;
    width: 100%;
    padding-bottom: 50%;
    position: absolute;
}
<div class="mydiv">
    this should be a fixed aspect ratio div
  </div
Itay Gal
  • 10,365
  • 6
  • 33
  • 73