You may see this problem, the first reaction is to use JS to get the width or height of the element, the event to listen for changes in the size of the element, set the width and height ratio.

But if you can use CSS, don’t use JS. So we can do this with the padding-top or padding-bottom of the element.

<style>
        #container {
            width: 50vw;
        }

        #box {
            padding-bottom: 50%;
            background: red;
        }
        
</style>
    
    <div id="container">
        <div id="box"></div>
    </div>
Copy the code

When the box is resized, the fixed ratio of width to height is 2:1.

Record the record!