Keith Power
Keith Power

Reputation: 14141

stop modal exceeding browser limits

I have a modal that I maintain an aspect ration of 16:9. It works well on most screens but of some if the browser is considerable wider than the height the modal streches above and below the browser.

Here is a DEMO. If you make the output panel wider the red modal exeeds the limits.

I would like to have the modal stop getting bigger when it reaches the top of the browser. I haven't been able to find a way to do it.

<div class="modal">
    Aspect is kept.
</div>

CSS

.modal {
    position: absolute;
    height: 0px;
    width: 80%;
    padding-bottom: calc(100% * 9 / 16);
    background-color: #F00;
    margin: auto;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
}

Upvotes: 1

Views: 108

Answers (3)

Rohit Kumar
Rohit Kumar

Reputation: 2031

I changed your css to this -

.modal {
    position: absolute;
    height: 0px;
    width: 80vw; /* Use 80% of viewport width */
    height: 45vw; /* use 45% of viewport Width so 16:9 ratio */
    max-height: 100vh; /* limits the height to not exceed viewport height */
    background-color: #F00;
    margin: auto;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
}

Fiddle

UPDATE: Fixed the 16:9 ratio bug on higher viewport size.
In the earlier fiddle the width keeps on increasing when the height reached its limit. To resolve this, add this line of css -

max-width: calc(100vh * 16/9);

Updated Fiddle

Upvotes: 1

Andrew
Andrew

Reputation: 39

The modal is actually not 16:9 in your example. If you change the padding-bottom to calc(80% * 9 / 16); it will be.

Aside from that I would try the vw/max-height solution proposed by Rohit.

Upvotes: 1

Maximillian Laumeister
Maximillian Laumeister

Reputation: 20359

Following is a solution that uses vmin to keep the modal from exceeding the boundaries of the window. An advantage of this solution is that it preserves the aspect ratio of your modal no matter how the window is resized.

.modal {
    position: relative;
    top: 50vh;
    transform: translateY(-50%);
    background-color: #F00;
    margin: auto;
    width: 90vmin;
    height: 63vmin;
}
<div class="modal">
    Aspect is kept.
</div>

JSFiddle Version: https://jsfiddle.net/gp6pbpov/2/

Upvotes: 0

Related Questions