How to create a responsive square image with CSS

Create a responsive square element containing an image using ::after pseudo class.

In this example the ‘.square’ will be a responsive square element. The relative position is only added to it to ensure the absolute position image is relative to it. The object fit and position allows the image to fill the space without being distorted.

.square {
  position: relative;
}

.square::after {
  content: "";
  display: block;
  padding-bottom: 100%;
}

.square img {
  position: absolute;
  width: 100%;
  height: 100%;
  object-fit: cover;
  object-position: 50% 50%;
}
Code language: CSS (css)

It’s work also noting that you don’t need to create a square, you can in fact create a rectangle of definite proportions by altering the padding-bottom value.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.