Perfectly square responsive images with CSS

Sometimes you need to have an image that is perfectly square even if the width of the image may change. To make a square responsive image we can utilize the fact that padding is dictated by an elements width. Let’s first look at how we can make a div square.

div {
    width: 100%;
    padding-bottom: 100%;
}

Utilizing padding-bottom we now have a div that has a responsive width and a height that is dictated by padding rather than the height property.

Now we can add our image as a background image and it will always be square.

div {
    width: 100%;
    padding-bottom: 100%;
    background-image: url("myimage.jpg");
    background-size: cover;
    background-position: center;
    background-repeat: no-repeat;
}