You can do this using pure CSS; no JavaScript needed. This utilizes the (somewhat counterintuitive) fact that padding-top percentages are relative to the containing block's width. Here's an example:
padding-top
.wrapper { width: 50%; /* whatever width you want */ display: inline-block; position: relative; } .wrapper:after { padding-top: 56.25%; /* 16:9 ratio */ display: block; content: ''; } .main { position: absolute; top: 0; bottom: 0; right: 0; left: 0; /* fill parent */ background-color: deepskyblue; /* let's see it! */ color: white; }
<div class="wrapper"> <div class="main"> This is your div with the specified aspect ratio. </div> </div>
2.1m questions
2.1m answers
60 comments
57.0k users