enforcing aspect ratios with padding

a handy css trick for when you need a box to maintain proportions (useful for handling images as backgrounds)

by jack gold

HTML

<div class="container">
    <div class="image-box"></div>
</div>

CSS

* {
    -moz-box-sizing: border-box;
    box-sizing: border-box;
    position: relative;
}
/* this is just to make our demo work better */
 .container {
    width: 80%;
    max-width: 600px;
    margin: auto;
}
.image-box {
    border: 1px dashed blue; /* again, just for our demo */
    
    background: url(//placehold.it/600x300/eee/ccc);
    background-size: cover;
    height: 0;
    padding-bottom: 50%; /* aspect ratio of picture - height/width */
}