How to vertically and horizontally center two images inside a div on a responsive page

1.9k Views Asked by At

I'm using Skeleton and Normalize css. I want to center two images side by side vertically and horizontally inside the div container. When the page becomes narrower, I want the 2nd image at the bottom of the first image as below

Normal width:
img1 img2

Narrow view:
img1
img2 

Here is my code:

<div id="center">
    <div class="left">
        <img class="u-max-full-width" src="img1.jpg">
    </div>        
    <div class="right">
        <img class="u-max-full-width" src="img2.jpg">
    </div>
</div>

And here is my css:

#center {
    width: 100%;
    text-align: center;
    position: relative;
    display: table;
}
#center > div {
    display: table-cell;
    vertical-align: middle;
}

.left {
    width: 50%;
    height: 100%;
    text-align: center;
}

.right {
    width: 50%;
    height: 100%;
    text-align: center;
}

With this code, they are vertically centered in normal width but I cannot get the images aligned below each other in narrower view. Any ideas on how to do this?

2

There are 2 best solutions below

9
Jip van Kakerken On BEST ANSWER

Try this:

.container {
  text-align: center;
  
  display: -webkit-box; /* OLD - iOS 6-, Safari 3.1-6 */
  display: -moz-box; /* OLD - Firefox 19- (buggy but mostly works) */
  display: -ms-flexbox; /* TWEENER - IE 10 */
  display: -webkit-flex;
  display: flex;
  
  justify-content: center;
  flex-wrap: wrap;

  -webkit-box-align: center;
  -webkit-flex-align: center;
  -ms-flex-align: center;
  -webkit-align-items: center;
  align-items: center;

  height: 800px;
}
<div class='container'>

   <img src="//placehold.it/300x300" class="thumbnail" alt="">
   
   <img src="//placehold.it/300x300" class="thumbnail" alt="">

</div>

Edit: Sry didn't read properly.. These don't break up if the page gets narrow.

As François pointed out, add this to the css:

flex-wrap: wrap;

Another Edit: apparently IE has some problems with this. Make a wrapper around .container (container_wrapper) or something. Give it:

display: flex;
flex-direction: column;
height: 100%;

And make sure your html and body are set to 100% height

0
François On

With the code of Jip van Kakerken, just add the property :

flex-wrap: wrap;

.container {
  text-align:           center;
  
  display:     -webkit-box; /* OLD - iOS 6-, Safari 3.1-6 */
  display:     -moz-box; /* OLD - Firefox 19- (buggy but mostly works) */
  display:     -ms-flexbox; /* TWEENER - IE 10 */
  display:     -webkit-flex;
  display:     flex;
  
  justify-content:      center;

  -webkit-box-align:  center;
  -webkit-flex-align:  center;
  -ms-flex-align:   center;
  -webkit-align-items:  center;
  align-items:    center;
  flex-wrap:            wrap;

  height:               800px;
}
<div class='container'>

   <img src="//placehold.it/300x300" class="thumbnail" alt="">
   
   <img src="//placehold.it/300x300" class="thumbnail" alt="">

</div>