Search code examples
htmlcssflexboxresizeviewport

How do I get two images to fit any screen size in html?


This is my first attempt at writing html so apologies in advance for any beginner-ish mistakes.

I want 2 images of equal size to sit in horizontal alignment in desktop/laptop and tablet browser windows, then once the screen switches to a mobile 'portrait' view I want the two images to align vertically, but still be entirely visible (i.e. the scroll bar does not appear).

I have got the first part of this working nicely by placing each image in a separate div and using flexbox. These two divs are within a container div. They are centering when in this view. Once the browser window gets too narrow the second image is placed below the first as expected, but it moves out of view. How can I ensure the images are resized to both remain in view the whole time?

  <style type="text/css">    
    html, body {
      height: 100vh;
      min-height: 100vh;
    }

    .call-outs-container {
      min-height: 100vh;
      height:auto !important;
      height:100vh;
      overflow: hidden !important;
      max-width: 2800px;
    }

    .pics {
      padding:20px;
      box-sixing: border-box;
      margin-bottom: 20px;
      flex-basis: 50%;
    }
    img {
      max-width:100%;
      height:100%;
      object-fit:contain;
    }

    @media (min-width: 700px) {
      .call-outs-container {
        display: flex;
        justify-content: space-between;
        position: absolute;
        top: 50%;
        left: 50%;
        margin-right: -50%;
        transform: translate(-50%, -50%);
      }
    }
  </style>
</head>
<body>
  <main>
    <div class="call-outs-container">

      <div class = "pics">
        <img src="images/temp_spectra.jpeg" alt="Spectra Image" />
      </div>
      <div class = "pics">
        <img src="images/temp_sl.png" alt="Spectra Image" />
      </div>

    </div>
  </main>
</body>

Following requests - here's a JSFiddle. https://jsfiddle.net/tullfan/t9hope6f/


Solution

  • You can try the vw (view width) and vh (view height) size for the height to use 50% of the whole view height by each of the 2 pictures. To fit the scale factor just set width to auto and the browser resizes the width so that the scale factor is same:

    img {
        height: 50vh;
        width: auto;
    }