Search code examples
htmlcssimageflexboxgrid

How to align images (with CSS) to a block of text on different screen widths?


Suppose we have block of text in the middle of the website, and two images - one to the left of the image, and one to the right of it.

However, on a device with smaller width, I want to have those 2 images under the text in a row. It seems simple but I didn't manage to come with an answer to that.

How it looks on a narrow screen:

How it looks on a narrow screen

How it looks on a wide screen:

How it looks on a wide screen

I tried using different media queries but I only managed to put all items in a column, which I don't want to do.


Solution

  • This can be done using css grids You have to use @media only screen and (max-width: {value}px) to add css properties for screens smaller than value pixels

    I think this is what you want :

    img{
      width: 100px;
      height: 200px;
      justify-self: center;
    }
    
    .text{
      text-align: center;
    }
    
    .container{
      display: grid;
      grid-template-columns: auto 2fr auto;
    }
    
    @media only screen and (max-width: 600px) {
      .text{
        grid-column : 1/4;
        grid-row: 1;
      }
      
      .img1{
        grid-column : 1;
        grid-row : 2;
      }
      
      .img1{
        grid-column : 3;
        grid-row : 2;
      }
    }
    <div class="container">
      <img class='img1' src=""/>
      <div class='text'>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus id lacus rutrum, auctor ligula imperdiet, porttitor ipsum. Proin a dolor quis felis pretium convallis. Cras nec accumsan neque. Vivamus nec venenatis lacus. Cras elementum id lorem sit amet iaculis. Pellentesque rhoncus a lorem a congue. Aenean suscipit est et est lacinia interdum. Pellentesque mattis odio scelerisque, sagittis lacus in, convallis leo.</div>
      <img class='img2' src=""/>
    </div>

    You could also change the grid-template-columns property for smaller screens to have a better result