有问题让图像在方形容器内正确居中

时间:2018-03-10 04:07:38

标签: html css html5 sass slick.js

我正在重新设计我的摄影网站,并为我的一些照片设置了一个简单的滑块。我有问题让图像以div为中心,并且周围有填充。我试图模仿照片在Instagram上的样子,它们在一个正方形中居中,但保持它们的宽高比。

以下是我的Codepen的link

我想要的例子:enter image description here

SCSS:

.slick-slider {
  .image_container {
    background: red;
    position: relative;
    overflow: hidden;
    height: 256px;
    padding: 20px;

    img {
      position: absolute;
      top: 0; bottom: 0; 
      margin: 0 auto;
      max-height: 300px;
      left: 0; right: 0;
      padding: 15px;
    }
  }
}

HTML:

<div class="slick-slider">
  <div class="image_container">
    <img src="http://cdn.jscotto.com/sites/joescottophotography.com/images/portraits/photo-portraits-1.jpg">
  </div>
  <div class="image_container">
    <img src="http://cdn.jscotto.com/sites/joescottophotography.com/images/portraits/photo-portraits-2.jpg">
  </div>
</div>

2 个答案:

答案 0 :(得分:0)

它会自动裁剪并适合div

.thumbnail {
  position: relative;
  width: 200px;
  height: 200px;
  overflow: hidden;
}
.thumbnail img {
  position: absolute;
  left: 50%;
  top: 50%;
  height: 100%;
  width: auto;
  -webkit-transform: translate(-50%,-50%);
      -ms-transform: translate(-50%,-50%);
          transform: translate(-50%,-50%);
}
.thumbnail img.portrait {
  width: 100%;
  height: auto;
}
<div class="thumbnail">
  <img src="http://cdn.jscotto.com/sites/joescottophotography.com/images/portraits/photo-portraits-5.jpg" alt="Image" />
</div>
<div class="thumbnail">
  <img src="http://cdn.jscotto.com/sites/joescottophotography.com/images/portraits/photo-portraits-2.jpg" class="portrait" alt="Image" />
</div>

答案 1 :(得分:0)

我最后搞砸了一会儿,想出了正确的css:

.image_container {
  margin: 0 10px;
  position: relative;
  overflow: hidden;
  height: 350px;
  background: rgba($offBlack, 0.05);

  img {
    position: absolute;
    top: 0; 
    bottom: 0; 
    left: 0; 
    right: 0;
    margin: auto;
    max-height: 300px;
    max-width: 310px;
  }
}