Aidar Amrekulov
Aidar Amrekulov

Reputation: 11

Stacking images on top of each other in a centered, responsive div

I have the following code. It is set up so that the images are responsive (scale with the window size) and positioned centrally, both horizontally and vertically. It was working fine until I wanted to add several images stacked on top of each other to play as a slideshow (fade-in, fade-out). I had to position the img tags "absolute". And it obviously collapsed the parent divs. Basically I want an alternative method to stack images on top of each other without using absolute positioning.

<div class="container">

            <div class="main-picture-wrapper">
                 <div class="main-picture">
                      <img id="front" src="img/VR-front.png" class="">
                      <img id="side" src="img/VR-side.png" class="">

                 </div>
             </div>
  </div>

 .container {
  height:100%;
  text-align: center;
  font:0/0 a;
    }

 .container:before {
  content: ' ';
  display: inline-block;
  vertical-align: middle;
  height: 100%;    
}

.main-picture-wrapper {
    margin-top: 70px;
    display: inline-block;
    vertical-align: middle;
    font-size: 16px/1;
    width:70%;
    left:0;      
}

.main-picture {
 width:100%;
 position: relative;
 text-align: center;
}

.main-picture img {
    position: absolute;
    width:100%;
    top: 0;
    left: 0;    

}

Upvotes: 1

Views: 3805

Answers (2)

Korbin
Korbin

Reputation: 578

If you don't have compatibility problem, you can always use flexbox solutions. You can check this website, it has some good examples http://www.sketchingwithcss.com/samplechapter/cheatsheet.html https://css-tricks.com/snippets/css/a-guide-to-flexbox/

Upvotes: 0

Lorenzo Marcon
Lorenzo Marcon

Reputation: 8179

As k185 suggested, flexbox is the way, along with absolute positioning. As today it's compatible with most of browsers.

Keeping your markup and style, a good starting point could be something like this:

html, body {
  height: 100%;
}

.main-picture {
  ...
  display: flex;
  align-items: center;
  justify-content: center;
}

.main-picture img {
  position: absolute;
}

https://jsbin.com/sinayiloge/edit?html,css,output

Upvotes: 3

Related Questions