jlitt1 jlitt1 - 5 months ago 15
Javascript Question

Centering image inside a full screen fixed div

I have a small image when clicked will use javascript to full screen the image inside the browser. When the browser is resized the image shrinks and provides a black background. using a auto on height is the problem but is needed for the scaling effect when the browser is shrunk.

I have tried:

transform: translate( 0,5%);
margin-top:50%;
position: absolute;
margin: auto;
top: 0;
left: 0;
right: 0;
bottom: 0;




$(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>




Answer

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

Comments