简体   繁体   中英

Keep aspect ratio of div. while using max-width

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.

You could apply the padding-bottom to its ::before pseudoelement, eg

.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 (eg the body element)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM