Search code examples
htmlcsscss-position

CSS positioning : inline image alignment issue


<div>
   <img class="top-cloud" src="images/cloud.png" alt="cloud-png">
   <h1>I'm Rithik.</h1>
   <p>B.E. Information Technology(IT) Student</p>
   <img class="bottom-cloud" src="images/cloud.png" alt="cloud-png">
</div>

If I define this div inside my webpage, the bottom-cloud image aligns itself just after the paragraph whereas If I add another image just after the bottom cloud(which is bigger in size than the bottom cloud).

<img src="images/mountain.png" alt="mountain-png">

The cloud image also moves down inline with the new image I inserted. Shouldn't cloud image remain at its previous position and the new image just comes after this. I have attached screenshots for better understanding. enter image description here

before adding another image.

enter image description here

After adding the mountain image why does the cloud also move down to align with the mountain?


Solution

  • If you want the 2 images to be on the same line, but aligned at the top instead of the bottom use vertical-align: text-top;

    By default it is set to baseline which is why they are aligned at the bottom.

    img {
      vertical-align: text-top;
    }
    
    #img1 {
      width: 40%;
    }
    #img2 {
      width: 20%;
    }
    <div>
      <img id='img1' src='https://media.sproutsocial.com/uploads/2017/02/10x-featured-social-media-image-size.png'>
      <img id='img2' src='https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRP3y-tITlqjr7xjuWA4ooxpP-z8OtoeNqacg&usqp=CAU'>
    </div>

    Why This Happens

    The image here is in black and the area it is sitting within is in blue. When you have 1 image these are the same size, because the image is the only thing within the area. 1 image diagram

    When you have 2 images (set with their default value to baseline) the area that the images are sitting in expands to fit around both images/all the content within the line. 2 Images aligned to baseline

    Changing vertical-align to text-top means both the images move to the top of the area, like this:

    2 images aligned to top

    In your example the area (blue box) is just the line that both the images are on, and it is working like this:

    Diagram to explain the website screenshot

    Whereas when you only had 1 image, the blue box was much smaller, since it was just the size of your smaller image.

    Diagram to explain the first website screenshot