将图像置于全屏固定div内

时间:2016-06-14 15:43:15

标签: javascript jquery html css

我有一些缩略图,当你点击每一个时,它会使用javascript来触发一个全屏覆盖,同时覆盖相同的图像但内部有更大的版本。

当浏览器窗口大小发生变化时,我需要将图像水平和垂直居中,并在黑色叠加层内自动调整大小。这是我试过的:



$(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>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:2)

您可以像这样设置全屏容器:

.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;
}

使用transform对图像进行居中:

.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