Fixed aspect ratio div limited to viewport, centered, maximum width and height

Is there a way to achieve this only in CSS, without JavaScript?

I need a div with the following requirements:

  • it ALWAYS maintains a given aspect ratio (for example, 4: 3).
  • its width never exceeds a given fixed maximum in px, for example. 800px
  • its height never exceeds a given fixed maximum, for example. 600px
  • its dimensions never exceed the dimensions of the viewport.
  • it is as large as it can get the above restrictions
  • it is centered both vertically and horizontally

In other words, it should fill either the width or height of the viewport, depending on which is more constraining, while maintaining this aspect ratio; if it does not exceed a fixed maximum width and / or height, in which case it will be limited to this.

I don't care how many wrappers inside inside I need.

I know this answer provides a solution to a fixed aspect ratio limited by the width of the parent, and it is easy to add a fixed max-width constraint with an additional wrapper; but I see no way to adapt this to add height restrictions.

+4
source share
2 answers

, max-height , . http://codepen.io/syren/pen/PNvorN

@mixin aspect-ratio($width, $height) {
    position: relative;
    max-width:400px;
    margin: 0 auto;
    display: block;

    &:before{
        display: block;
        content: " ";
        width: 100%;

        padding-top: ($height / $width) * 100%;
    }

    > .content {
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
    }
}

.sixteen-nine {
  @include aspect-ratio(16,9);  
}

, , , . max-height, 0, , , , 0 padding-left padding-top bottom . -. , .

, -.

/ /? https://dev.opera.com/articles/css3-object-fit-object-position/

!

+1

css flex. , display: flex. . / .

, : div CSS

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

.center {
    display: flex;
    justify-content: center;
    align-content: center;
    align-items: center;
    align-self: center;
    flex: 1 0 auto;
    height: 100%;  
    width: 100%;
}

.center > div {
    align-self: auto;
    background-color: #aaa;
}

.container {
    width: 100%;
    padding-bottom: 75%; /* achieves 4:3 aspect ratio */
    margin: 0 20px;
    background-color: yellow;
}

.centered {
    max-width: 800px;
    max-height: 600px;
    width: 100%;
    height: 100%;
}
<!-- ... -->
<div class='center'>

    <div class='container'>

        <!-- ensure your .centered div has 
        some specified height & width -->
        <div class='centered'>
            Your content
        </div>

    </div>

</div>
<!-- ... -->

JSBin Demo Here

0

All Articles