Responsively change div size keeping aspect ratio

ilyo picture ilyo · Aug 25, 2012 · Viewed 195.1k times · Source

When I give an image a percent width or height only it will grow/shrink keeping its aspect ratio, but if I want the same effect with another element, is it possible at all to tie the width and the height together using percentage?

Answer

Chris picture Chris · Aug 25, 2012

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:

.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>