简体   繁体   中英

Centering image inside a full screen fixed div

I have some thumbnail images, when you click on each one, it will use javascript to trigger a full screen overlay with the same image but larger version inside.

I need the image to be horizontally and vertically centered and resized automatically inside the black overlay when the browser window size changes. Here is what I tried blow:

 $(document).ready(function() { $('.gallery_pics').click(function(e) { $(this).toggleClass('fullscreen'); }); }); 
 .gallery_pics_holder { border: px solid green; width: 100%; text-align: center; height: 350px; display: table; } .gallery_pics { display: inline-block; width: 150px; height: 150px; margin: 10px; text-align: center; background-color: #3C0; } .gallery_pics img { width: 100%; height: 100%; } .gallery_pics:hover { cursor: pointer; } .gallery_pics.fullscreen { z-index: 9999; position: fixed; margin: 0 auto; width: 95%; height: 95%; top: 2%; left: 3%; background-color: #000; display: inline-table; } .gallery_pics.fullscreen img { margin: 0 auto; text-align: center; max-width: 1099px; height: auto; vertical-align: middle; text-align: center; display: table-cell; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <div class="gallery_pics_holder"> <div class="gallery_pics"> <img src="http://lorempixel.com/800/800/sports/1"> </div> <div class="gallery_pics"> <img src="http://lorempixel.com/800/800/sports/2"> </div> <div class="gallery_pics"> <img src="http://lorempixel.com/800/800/sports/3"> </div> <div class="gallery_pics"> <img src="http://lorempixel.com/800/800/sports/4"> </div> <div class="gallery_pics"> <img src="http://lorempixel.com/800/800/sports/5"> </div> <div class="gallery_pics"> <img src="http://lorempixel.com/800/800/sports/6"> </div> <div class="gallery_pics"> <img src="http://lorempixel.com/800/800/sports/7"> </div> <div class="gallery_pics"> <img src="http://lorempixel.com/800/800/sports/8"> </div> <div class="gallery_pics"> <img src="http://lorempixel.com/800/800/sports/9"> </div> </div> 

You can set the full screen container like this:

.gallery_pics.fullscreen {
  z-index: 9999;
  position: fixed;
  margin: auto;
  width: 95%;
  height: 95%;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  background-color: #000;
}

And using transform for centering the image:

.gallery_pics.fullscreen img {
  max-width: 90%;
  max-height: 90%;
  width: auto;
  height: auto;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
}

jsFiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM