htmlcssaspect-ratio

Child div ignore parent aspect-ratio 16/9 and content inside parent and push content down


enter image description hereI have parent div with aspect-ratio: 16/9; and inside that div I have another div with same ratio, but I also have some content with that child inside, when I set child aspect-ratio it's move content down and change height of the parent and parent lose the ratio? Is there a way for preventing this? codepen

<div class="container">
    <div class="container-2"></div>
    <div class="content">
        Lorem ipsum dolor sit amet consectetur, adipisicing elit. Quibusdam quisquam, tempore harum commodi beatae earum aperiam! Beatae et nulla alias.
    </div>
</div>
.container {
    aspect-ratio: 16/9;
    background: #ccc;

    
    .content {
        font-size: 2rem;
        padding: 1rem;
    }
    .container-2 {
        aspect-ratio: 16/9;
        max-height: 100%;
        background: blue;
    }
}

Solution

  • Use CSS grid

    .container {
        aspect-ratio: 16/9;
        background: #ccc;
        display: grid;
        grid-template-rows: 1fr auto; /* the first row will take the available space */
        
        .content {
            font-size: 2rem;
            padding: 1rem;
        }
        .container-2 {
            aspect-ratio: 16/9;
            min-height: 100%; /* 100% height of the available space */
            margin: auto; /* center */
            background: blue;
        }
    }
    <div class="container">
        <div class="container-2"></div>
        <div class="content">
            Lorem ipsum dolor sit amet consectetur, adipisicing elit. Quibusdam quisquam, tempore harum commodi beatae earum aperiam! Beatae et nulla alias.
        </div>
    </div>