【问题标题】:Center fit images of any size to parent div中心适合任何大小的图像到父 div
【发布时间】:2019-07-14 16:30:18
【问题描述】:

我有一个图像滑块,所选图像设置为上面的主图像。所有图像的大小都不相同。如何确保每个图像在父 div 和整个父 div 中居中?

我现在正在这样做:

width: 100%;height: 100%;object-fit:fill;

但随后我的图像丢失了其内容的底部。我想将图像垂直居中。

我的父 div 具有以下类样式:

.wrapper_image{
    max-width:100%;
    max-height:100%;
    min-height:100%;
    min-width: 100%;
    margin: 0 auto;
}

代码:

<div class="o-grid__col u-12/12" style="width: 400px;
          height: 400px;
          position: relative;
          display: inline-block;
          overflow: hidden;
          text-align: center;
          margin: 0;">
          <div class="mySlides wrapper_image_horses">
          <img src='url' style="width: 100%;height: 100%;object-fit:fill;">
          </div>
</div>

【问题讨论】:

  • 你为什么使用内联css?它只会带来问题......
  • 仅供测试
  • 在互联网幻灯片中输入您会看到大量示例
  • 是的,但我需要这个:p
  • 你能做个小提琴吗?还是codepen?

标签: html css


【解决方案1】:

我建议你使用display: flex; 来实现这一点。使用 flex,您可以更轻松地将图像垂直和水平居中对齐。下面是我做过的测试代码。希望对你的问题有所帮助

HTML

<div class="d-flex h-100">
  <div class="img-slide">
    <img src="https://via.placeholder.com/150">
  </div>
</div>

CSS

.d-flex {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: center;
}

.h-100 {
  height: -webkit-fill-available;
}

JS 小提琴链接:https://jsfiddle.net/SJ_KIllshot/y5fzvox8/

【讨论】:

    【解决方案2】:

    这是一个现代的解决方案,希望对您有所帮助

    DEMO

    <div class="o-grid__col u-12/12" style="width: 400px;
          height: 400px;
          position: relative;
          display: inline-block;
          overflow: hidden;
          text-align: center;
          margin: 0;
          border: 1px solid #000;">
          <div class="mySlides wrapper_image_horses" style="position: absolute;
                      top: 50%; left: 50%;
                      transform: translate(-50%,-50%);">
            <img src='https://picsum.photos/id/159/200/200' style="width: auto;height: auto;">
          </div>
    

    【讨论】:

    • 使用这个,图像显示在他原来的形状
    • 我发现了以下内容。图像在弹出窗口中。垂直对齐在整页上,但不在弹出窗口上
    • @belgiums 你成功解决了这个问题吗?
    猜你喜欢
    • 2013-08-09
    • 1970-01-01
    • 2015-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-13
    • 2015-07-30
    • 1970-01-01
    相关资源
    最近更新 更多