1
votes

I know I can achieve responsive square divs that maintain their apsect ratio using CSS like this:

The problem is, the div size is always relative to the parent/window. I would like the div to have a fixed max width as long as the window/screen isn't smaller. As you would with a normal responsive image. Is this even possible?

I tried...

.some-class {
  width: 100%;
  padding-bottom: 100%;
  max-width: 520px;
}

The div maintains its aspect ratio width a 520px width but when the screen is smaller, the height stays the same. So I get more height, instead a square div. It doesn't keep the aspect ratio.

1
use % max width not px - ProEvilz
@CyberJ have you tried my answer? - Fabrizio Calderan
@fcalderan yes it works great! Thank you! Voted - CyberJ

1 Answers

5
votes

You could apply the padding-bottom to its ::before pseudoelement, e.g.

.some-class {
  width: 100%;
  max-width: 520px;
  border: 1px #9bc solid;
}
.some-class::before {
   padding-bottom: 100%;
   content: "";
   display: inline-block;
   vertical-align: top;
}

demo

Doing so the padding is always computed relatively to the actual width of the div and not to the width of its ancestor (e.g. the body element)


Update (05/2021)

On recent browsers you could start using the new aspect-ratio property, so if the browser supports it you could simply write

.some-class {
  width: 100%;
  max-width: 520px;
  border: 1px #9bc solid;
  aspect-ratio: 1;
}