CSS to Maintain Aspect Ratio

Here’s a cool trick on how to maintain a div’s aspect ratio when working with responsive designs.

CSS

.four-three {
    padding-bottom: 75%;
    width: 100%;
    background-color:silver;
}

This trick can be really powerful when combined with a responsive CSS framework like Bootstrap. A common use case is a row of images that need to retain their row height.

CSS

.four-three {
    padding-bottom: 75%;
    width: 100%;
    background-color:#eee;
    position:relative;
}
.four-three > div {
    position:absolute;
    top:5px;
    bottom:5px;
    left:5px;
    right:5px;
    background-size: contain !important;
}

HTML

The Result

This works well with background-size: cover; to stretch the image to fill the div.