1

I have this situation in which I want to render a div as a square, where the height determines the width. So far the only solution which comes very close is to use an 1px by 1px image:

<div class="square">
    <img src="data:image/gif;base64,R0lGODlhA...RAA7">
</div>

.square {
    display:inline-flex;
    height:100%;
    background:darkorange;
}

img {
    display:block;
    height:100%;
    width:auto;
}

(Source) JSFIDDLE

But whatever I try, when I change the height, the square is stretch vertically (not a square any more). You have to hit reload to make it a square again. This seems to happen only in Chrome. Although in the original post it is suggested to use display: inline-flex for .square it doesn't seem to work. Maybe I did missed something. Any suggestions?

Jeanluca Scaljeri
  • 26,343
  • 56
  • 205
  • 333
  • 1
    without playing around with your code i have a question, have you tried using `width: 100%;` `height: auto` instead? – cup_of Mar 16 '18 at 22:47
  • 1
    I did this case with padding-bottom (%) and image proportion. So you should use padding-bottom:100% on .square in your case and position:absolute; witdth:100%; height:100% on img. https://jsfiddle.net/0zgh8a4t/ – Anon Mar 16 '18 at 22:53
  • Possible duplicate of [Maintain the aspect ratio of a div with CSS](https://stackoverflow.com/questions/1495407/maintain-the-aspect-ratio-of-a-div-with-css) – showdev Mar 16 '18 at 23:05
  • 1
    I trick this with some javascript https://jsfiddle.net/3vjh0s3j/. – User 28 Mar 17 '18 at 04:57
  • 1
    And this with some css animation https://jsfiddle.net/aLgd2917/. – User 28 Mar 17 '18 at 07:30
  • Thanks for the help. This question is not a duplicate of [Maintain the aspect ratio of a div with CSS](https://stackoverflow.com/questions/1495407/maintain-the-aspect-ratio-of-a-div-with-css) because in that post its all about the aspect ratio given a certain width. I have a given `height` and no `width`. Only the above 2 comments seem to have a working fix for this issue! – Jeanluca Scaljeri Mar 17 '18 at 09:47

0 Answers0