RedRK9
RedRK9

Reputation: 23

HTML - Fitting images in multiple rows to fit viewport

I am developing a website, in which I display N amount of images. A good example of how I would like to display them is how DeviantArt does it. Images are shown in rows in such a way that it fills the width of the current viewport and does not deform any images.

My attempt was the following:

#CSS
  .item {
    display: inline-block;
    vertical-align: top;
    position: relative;
    overflow: hidden;
    padding: 0.5em;
    background: lightcoral;
    border: black solid 1px;
  }
  .item img{
    max-height: 200px;
    object-fit: scale-down;
  }
HTML
    <div style="display: block; width: 100%">
      <!-- A vue directive, used in this example to render this element n amount of times per images -->
      <div class="item" v-for="(i, index) in images" :key="index">
        <img :src="i.url">
        <div style="display: flex; flex-direction: column;">
          <div>{{i.title}}</div>
          <div>By User1234</div>
        </div>
      </div>
    </div>

Which results in the following: enter image description here

As you can see, there are gaps left at the end of each row. Id like for each row to be able to fit all possible images so that the grid fits the viewport, like this:

enter image description here

Im very interested to know how I can achieve this, either by using pure HTML / CSS or Javascript if needed.

Upvotes: 0

Views: 123

Answers (1)

Andrew Hulterstrom
Andrew Hulterstrom

Reputation: 1725

You probably want to use flexbox with flex-grow. CSS-Tricks has a great article on this here: https://css-tricks.com/piecing-together-approaches-for-a-css-masonry-layout/

Here's a codepen from the article:

codepen

    body {
  margin: 0;
  padding: 1rem;
}

.masonry-with-columns {
  display: flex;
  flex-wrap: wrap;
  div {
    height: 150px;
    line-height: 150px;
    background: #EC985A;
    color: white;
    margin: 0 1rem 1rem 0;
    text-align: center;
    font-family: system-ui;
    font-weight: 900;
    font-size: 2rem;
    flex: 1 0 auto;
  } 
  @for $i from 1 through 36 { 
    div:nth-child(#{$i}) {
      $h: (random(400) + 70) + px;
      width: $h;
    }
  }
}

Upvotes: 1

Related Questions