CSS properties - aspect-ratio

revision:


aspect-ratio property

The aspect-ratio property allows you to define the ratio between width and height of an element. If "aspect-ratio" and "width" properties are set, the "height" will follow in the defined aspect ratio.

Use the aspect-ratio property in responsive layouts where elements often vary in size and you want to preserve the ratio between width and height.

CSS syntax : aspect-ratio: number/number|initial|inherit;

Property values

number : first number specifies the number for width in aspect ratio.

number : second number specifies the number for height in aspect ratio. Optional. If not set, number for height is 1 as default.

initial : sets this property to its default value.

inherit : inherits this property from its parent element.

JavaScript syntax: object.style.aspectRatio="16/9"

example: aspect-ration property
Hello
holiday
holidays
bath: width=
sailing
code:
                    <div>
                        <div id="div1">Hello</div>
                        <div ID="container">
                            <div class="first"><img src="../pics/1.jpg" alt="holiday" width="460" height="345"></div>
                            <div class="first"><img src="../pics/2.jpg" alt="holidays" width="460" height="345"></div>
                            <div class="first"><img src="../pics/3.jpg" alt="bath: width="600" height="400"></div>
                            <div class="first"><img src="../pics/4.jpg" alt="sailing" width="600" height="400"></div>
                        </div>
                    </div>
                    <style>
                        #div1 {background-color: red; width: 9vw; aspect-ratio: 3/2;}
                        #container {display: grid; width: 90%; margin: auto; border: solid black 0.2vw; 
                            grid-template-columns: repeat(auto-fit, minmax(15vw, 1fr)); gap: 1vw; padding: 1vw;}
                        #container > div .first{aspect-ratio: 3 / 2;}
                        img { width: 100%; height: 100%; object-fit: cover; object-position: center;}
                        
                    </style>