Hello, I want to maintain an aspect ratio of a div using CSS, I know we can do it with javascript also, but I would like to maintain aspect ratio using CSS only.
Is there any way to change height according to width, maintaining the aspect ratio using any CSS rule or property?
You can use vw unit to specify width & height, it will make your div
aspect ratio using CSS according to the viewport width(vh is used to keep aspect ratio according to viewport height)
1vw : 1% of the width of the viewport, check here
To keep 1:1 aspect ratio viewport css would be
div{
width: 25vw;
height:25vw;
background:yellow;
}
HTML : <div></div>
For other aspect ratios, you can use the following table to calculate the value for height according to the width of the element:
aspect ratio | multiply width by
-----------------------------------
1:1 | 1
1:3 | 3
4:3 | 0.75
16:9 | 0.5625
Check this fiddle example.I hope this works for aspect ratio using css, thanks
Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly