Search code examples
cssposition

How to arrange images in a div evenly without breaking their aspect ratio


I think I'll best explain myself when I show my failed attempts:

Attempt 1. margin auto

div {
    height: 50px;
    width: 500px;
    border: 1px solid black;
}

div > img {
    height: 100%;
    display: block;
    margin: 0 auto;
}
<div>
    <img src="https://upload.wikimedia.org/wikipedia/commons/a/a6/U%2B25C9.svg"/>
    <img src="https://upload.wikimedia.org/wikipedia/commons/a/a6/U%2B25C9.svg"/>
    <img src="https://upload.wikimedia.org/wikipedia/commons/a/a6/U%2B25C9.svg"/>
</div>

See? I have a div and I want to arrange these circles in this div evenly. Sadly, with the current approach, they won't sit next to each other but rather, they're stacking themselves in a pillar.

Attempt 2. flex

div {
    height: 50px;
    width: 500px;
    border: 1px solid black;
    display: flex;
}

div > img {
    height: 100%;
    flex: auto;
}
<div>
    <img src="https://upload.wikimedia.org/wikipedia/commons/a/a6/U%2B25C9.svg"/>
    <img src="https://upload.wikimedia.org/wikipedia/commons/a/a6/U%2B25C9.svg"/>
    <img src="https://upload.wikimedia.org/wikipedia/commons/a/a6/U%2B25C9.svg"/>
</div>

Now the circles are evenly arranged BUT the aspect ratio is screwed.

No, I cant just set width to the desired value, because 1) it doesn't seem to be working 2) even if it was working, the height of the div is specified in percentages of the enclosing container (here I specified it in px for the sake of simplicity) so I don't know which value to put there

Any way to distribute the circles evenly in the div without breaking aspect ratio?


Solution

  • You are almost good with the flexbox approach. Don't make the element growing so don't set flex to auto which will set flex-grow:1

    div {
      height: 50px;
      width: 500px;
      border: 1px solid black;
      display: flex;
      justify-content: space-around;
    }
    
    div>img {
      height: 100%;
      /*Or margin:auto instead of justify-content: space-around*/
    }
    <div>
      <img src="https://upload.wikimedia.org/wikipedia/commons/a/a6/U%2B25C9.svg" />
      <img src="https://upload.wikimedia.org/wikipedia/commons/a/a6/U%2B25C9.svg" />
      <img src="https://upload.wikimedia.org/wikipedia/commons/a/a6/U%2B25C9.svg" />
    </div>