Home  >  Q&A  >  body text

Implementing a Pinterest-like CSS grid of dynamic images in React

So I'm trying to use CSS Grid to make a Pinterest-like image gallery. So pictures of different heights can be next to each other, and each picture can take up empty space. But all the examples I've seen add different classes on each image based on the height they want, whereas I want to add images dynamically from the database.

I tried doing this:

<div className=‘gallery’>
<img className=‘image’> </img>
<img className=‘image’> </img>
<img className=‘image’> </img>
<img className=‘image’> </img>
</div>

My CSS file:

.gallery{
max-width: 80vh;
display: grid;
grid-template-columns:repeat(3,1fr);
}

.image{
max-width: 200px;
height: 100%;
object-fit: cover;
}

But so the small pictures are on the same row and the big pictures are on another row, and I want them to be random.

Is there a way to achieve this without adding a different class for each image?

P粉614840363P粉614840363184 days ago412

reply all(1)I'll reply

  • P粉214089349

    P粉2140893492024-03-22 12:48:04

    Pinterst uses vertical alignment. So, if you want to duplicate it, you should create vertical boxes that are adjacent and have a fixed width. And display as many rows as fit the size of the screen. (If you resize the Pinterest window, the entire page will regenerate, but that's outside the scope of your question, I guess) So I recommend using a div or even a table with just one row and one long column.

    <table>
      <tr>
        <td>图片</td>
        <td>图片</td>
        <td>图片</td>
      </tr>
    </table>

    Of course it is dynamic. (I created a long row with 3 columns for smaller screens) From here, you can add images to each column, setting the width of the tr to 200px and the width of the image to 100%.

    reply
    0
  • Cancelreply