1

I don't know how but I've been at this for hours and can't figure it out.

I'm trying to make a div have a fixed aspect ratio of 1:1, but the padding-top trick just isn't working.

Here is my code:

HTML:

<div class="test">
  <div/><div/><div/><div/>
</div>

CSS:

.test {
  width: 50px;
  height: 0px;
  padding-top: 100%;
  background: blue;
}

Can anyone figure what I am doing wrong?

JSFiddle link: http://jsfiddle.net/ajpgbc0L/

Expected result: http://jsfiddle.net/ajpgbc0L/2/

EDIT: I should have made it clear that the width could be anything

Asons
  • 84,923
  • 12
  • 110
  • 165
David Callanan
  • 5,601
  • 7
  • 63
  • 105
  • 1
    euh, and since you div has a fixed width why bothering with padding? simply set the needed height – Temani Afif Dec 11 '18 at 19:26
  • I should have made it clear that the width could be anything... – David Callanan Dec 12 '18 at 21:17
  • [It is absolute a dupe](https://stackoverflow.com/questions/1495407/maintain-the-aspect-ratio-of-a-div-with-css), whether you use 100% or not. Just read through the answers and you'll find those using a wrapper, which is what is needed, or a pseudo element, which is another solution also shown in the dupe. – Asons Dec 12 '18 at 21:23
  • @LGSon let's add more dup link then .. people don't check all the answer, don't check the related question, don't read comments, etc – Temani Afif Dec 12 '18 at 21:26
  • @TemaniAfif Great...and do, as someone (or queue) reopened this after I closed it. – Asons Dec 12 '18 at 21:26
  • 1
    in case you still don't agree, here is an answer like the one you accepted : https://stackoverflow.com/a/12121309/8620333 – Temani Afif Dec 12 '18 at 21:27
  • @LGSon it's wasn't someone, it's seems the reopen queue and most of the users aren't active on the CSS tag – Temani Afif Dec 12 '18 at 21:28

1 Answers1

5

Adding a wrapper element around it with a set width will allow you to achieve the desired result:

<div class="test__outer">
  <div class="test">
    <div/><div/><div/><div/>
  </div>
</div>

css:

.test {
  height: 0px;
  padding-top: 100%;
  background: blue;
}

.test__outer {
  width: 50px;
}

This is because precent padding is calculated, based on the width of the containing block, not the block you are setting padding on: https://developer.mozilla.org/en-US/docs/Web/CSS/padding#Values

Gleb Kostyunin
  • 3,743
  • 2
  • 19
  • 36