简体   繁体   中英

How do I make the items change in size according to the window size inside a flexbox?

I've created a basic image gallery using flexbox in html/css. There are six images on the page currently, and due to flex-wrap they change configuration from 1x6 to 2x3 to 3x2 to 4+2 to 5+1 to 6x1 according to the window size. Now I want to incorporate 2 further features:

  1. The scaling shouldn't go beyond 3x2, to maintain the symmetry of the website. After 3x2, just the size of the images should increase
  2. The sizes of images should also scale according to the window. For example, as i increase window size in a 2x3 configuration, the image sizes should also increase till it reaches the 3x2 configuration. This is to ensure the images take up the full width of the window (barring some padding) I've tried percentage width, but it's really not compatible with flexbox.

Following is the html:

 .row { display: flex; flex-wrap: wrap; justify-content: center; align-items: center; margin: 150px; }.image { min-width: 30%; flex-grow: 1; transition: 0.2s; padding: 0 2vw 4vw; margin: 20px 10px 20px; }
 <.--Image gallery--> <div class="container"> <a href="test_image.jpeg"> <div class="image"><img src="test_image.jpeg" href="test_image"></div> </a> <a href="test_image.jpeg"> <div class="image"><img src="test_image.jpeg" href="test_image"></div> </a> <a href="test_image.jpeg"> <div class="image"><img src="test_image.jpeg" href="test_image"></div> </a> <a href="test_image.jpeg"> <div class="image"><img src="test_image.jpeg" href="test_image"></div> </a> <a href="test_image.jpeg"> <div class="image"><img src="test_image.jpeg" href="test_image"></div> </a> <a href="test_image.jpeg"> <div class="image"><img src="test_image.jpeg" href="test_image"></div> </a> </div>

To make the images scale to fill the container, set justify-content: stretch on the row div, set flex-grow: 1 on the image container div, and width: 100% on the image itself. Setting min-width on the image div around 30% will keep it <= 3 images per row.

.row {
    display: flex;
    flex-wrap: wrap;
    justify-content: stretch;
    align-items: center;
    margin: 150px 40px;
}

.image {
    padding: 0 20px 40px;
    min-width: 25%;
    flex-grow: 1;
}

img {
    width: 100%;
}

Here's a fiddle with an example (it's hard to see it working with a container this small, but you can tell if you zoom out): https://jsfiddle.net/817o6r0f/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM