Implementing a Pinterest-like CSS grid of dynamic images in React
P粉614840363
P粉614840363 2024-03-21 20:21:31
0
1
523

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粉614840363
P粉614840363

reply all(1)
P粉214089349

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%.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template