【问题标题】:Having issues getting images centered properly inside of square container在方形容器内正确居中图像时遇到问题
【发布时间】:2018-03-10 04:07:38
【问题描述】:

我正在重新设计我的摄影网站,并正在为我的一些照片设置一个简单的滑块。我在让图像在 div 中居中并到处填充时遇到问题。我试图模仿照片在我的Instagram 上的外观,它们以正方形为中心,但保持纵横比。

这是我的 Codepen 的 link

我的目标示例:

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>

【问题讨论】:

  • 最简单的方法是在将所有图像加载到滑块之前,确保所有图像尺寸相同,并进行裁剪。
  • 你的代码笔,以及“我要做什么”的形象;对我来说,两者看起来图像都以相同的方式居中。 codepen 看起来它做了你想做的事情。我不确定要问什么
  • @chiliNUT 那是因为我最终弄清楚了,现在要发布答案。 SO上的代码是原始的非工作代码。

标签: css html sass slick.js


【解决方案1】:

它会自动裁剪并适合 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>

【讨论】:

    【解决方案2】:

    我最终搞砸了一段时间并找出了正确的 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;
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2015-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-03
      • 1970-01-01
      • 2017-09-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多