0

If I have an element (such as div#frame) that I want to populate as much of the screen as it can while still maintaining a designated aspect ratio (such as 16:9), what styles must I apply? I am certain there are a handful of different solutions in Javascript, but I want to try an approach with only CSS.

I've searched around, and although there are already some solutions in CSS, they use a percentage padding, which is calculated by the value of the width, which means the aspect ratio is only maintained when the browser is horizontally resized, and not vertically resized.

#frame
{
    /* centered */
    top: 0px;
    left: 0px;
    right: 0px;
    bottom: 0px;
    margin: auto;
    position: fixed; 

    /* aspect ratio */
    width: 100%;
    height: 0px;
    padding-bottom: 56.25%;
}

This works good enough, but I want a solution that will still maintain the aspect ratio of the element when resized both horizontally and vertically, as seen in the image I've embedded below.

enter image description here

Kunj
  • 1,980
  • 2
  • 22
  • 34
Arcym
  • 500
  • 4
  • 13

1 Answers1

1

I don't think it is possible to set the width of an element based on the height, using css properties as they were meant to be used. So you better start considering JS there ;) There is a hack involving an image though, but it is not great. Maybe you can expand on the idea (I would still prefer JS).

You will need an image with the maximum size you want your frame to be. A transparent gif should do. Then you let the native behaviour of the image set the wrapper's size, using inline-block on the wrapper. Then you use an absolutely positioned element inside the wrapper to hold your content:

<div class="wrapper">
    <img src="https://cdn.boldernet.net/0/0/856/856567-450.jpg">
    <div class="content">
        content
    </div>  
</div>

CSS:

body {
    text-align: center;
}

.wrapper > img {
    display:block;
    max-width: 100%;
    max-height: 100%;
}
.wrapper {
    display: inline-block;
    position: relative;
    top: 50%;
}
.content {
    position: absolute;
    background: blue;
    left: 0;
    top: -50%;
    width:100%;
    height:100%;
}
Hugo Silva
  • 6,748
  • 3
  • 25
  • 42