Search code examples
imageresponsive-designvertical-alignment

Responsive design image aligning


I am a novice html/CSS programmer who needs to satisfy a very specific set of circumstances. I have 2 images, both must be aligned vertically by the center of the image. One image must be left aligned and the other must be right aligned. They will be in a max width div but I don't think that should be an issue. As the webpage is shrunk down below the width of the two pictures together, the images then need to be horizontally centered with one image on top of the other. I have added pictures to clarfiy (sorry I would have added as pictures but I have zero rep). The div container and images will all be variable so positioning based upon pixels is out of the question.

So I researched this a ton, but all answers I've found have been partial; not able to do everything I'm looking for. Any ideas?

(http://imageshack.us/a/img819/9515/3zt.gif)

(http://imageshack.us/a/img14/853/qp8.gif)

Research:
I notice my question was -1'd. I guess not providing my research was the fault? Here's some of the methods I tried to fix this issue: Vertical alignment of elements in a div

How to vertically align an image inside div

How to vertically middle-align floating elements of unknown heights?

Wrap long HTML tables to next line


Solution

  • Edit #2

    Another version, I think this is the cleanest I can think of
    live view
    edit view
    Use a css table and vertical-align:middle for the wide screen view, then collapse the table for narrow viewports. The code is clean and it's completely independant of image heights.

    ================

    Edit

    As @user2748350 correctly pointed out, my original suggestion below didn't align images vertically on a wide screen if they were different heights.

    Here's a variation which is an improvement using vertical-align: middle and inline images. The only requirement is that you set a line height larger than the tallest image:
    live view
    edit view

    ===============================================
    Original

    See if this helps you:
    live view
    edit view

    HTML

    <div class="container">
    <img src="http://placehold.it/300x150" class="left">
    <img src="http://placehold.it/250x150" class="right">
    </div>  
    

    CSS

    .container{
    margin: 0 auto;
    max-width:1000px;
    }
    img.left{
    display:block;
    float:left;
    }
    img.right{
    display:block;
    float:right;
    }
    
    @media (max-width: 570px) {
    img.left{
    float:none;
    margin: 0 auto;
    }
    img.right{
    display:block;
    float:none;
    margin: 0 auto;
    }
    }  
    

    In the head of your page, you also want to add

    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    

    for good display on mobile devices.

    Hope this helps!