Search code examples
cssimagealignmentgallery

align images left and right automatically in css


I've been working on a page and there's some sort of gallery that needs to be done. I have to align the images alternately. For example: the first image is aligned left and the second is aligned right, and this should continue automatically. Do you have any idea on how to do that? (if it's even possible)

Greetings :)


Solution

  • for example with grid container and :nth-child(even) or :nth-child(odd)

    .container {
      display: grid;
    }
    img:nth-child(even) { justify-self: left;}
    img:nth-child(odd) { justify-self: right; }
    <div class="container">
      <img src="https://picsum.photos/200/300" />
      <img src="https://picsum.photos/200/300" />
      <img src="https://picsum.photos/200/300" />
      <img src="https://picsum.photos/200/300" />
      <img src="https://picsum.photos/200/300" />
      <img src="https://picsum.photos/200/300" />
      <img src="https://picsum.photos/200/300" />
    </div>