Search code examples
htmlcssimageresponsive-designresponsive

Display and resize multiple images according to browser width


I'd like to be able to display up to 5 images on the same line, depending on the browser width.

Depending on the browser size, I can display more or fewer images, from a single image on mobile to a maximum of 5 on desktop.

The images are resized according to the browser size and are displayed or hidden according to some breakpoints.

Image resizing and displaying

Does anyone have any ideas on how to do this?


Solution

  • There're several way to accomplish what you want but, basically, you'll have to use CSS media queries to do it:

    * {
      box-sizing: border-box;
      margin: 0;
      padding: 0;
    }
    
    #container {
      display: flex;
      gap: 1rem;
    }
    
    img { 
      width: 100%;
      display: none;
    }
    
    @media (min-width: 200px) {
      #image1 { display: initial; }
    }
    
    @media (min-width: 400px) {
      #image2 { display: initial; }
    }
    
    @media (min-width: 600px) {
      #image3 { display: initial; }
    }
    
    @media (min-width: 800px) {
      #image4 { display: initial; }
    }
    
    @media (min-width: 1000px) {
      #image5 { display: initial; }
    }
    
    
    
    <div id="container">
      <img id="image1" src="https://picsum.photos/300">
      <img id="image2" src="https://picsum.photos/300">
      <img id="image3" src="https://picsum.photos/300">
      <img id="image4" src="https://picsum.photos/300">
      <img id="image5" src="https://picsum.photos/300">
    </div>
    

    See it on Codepen